Java Basics Chapter
Literals Interview Questions and Answers
Learn how Java literals work, from integer, floating-point, and character literals to escape sequences, Unicode escapes, string pooling, and boolean/null literals.
Literals interview questions
Literals Interview Question 15 Questions
Click on any question to expand the answer.
Interview Answer
A literal is a fixed value written directly in Java source code, such as 100, 3.14, 'A', or "Java". A variable is a named memory location whose value can change, while a constant is a variable declared with final whose value cannot be reassigned after initialization.
Key Points
- Literals directly represent values in source code.
- Variables store values and may change during execution.
- Constants are declared using the final keyword.
- Literals do not have names, but variables and constants do.
- A literal can be assigned to a variable or constant.
- Every literal has a data type determined by its form.
Syntax
dataType variableName = literal;
final dataType CONSTANT_NAME = literal;Example
public class LiteralExample {
public static void main(String[] args) {
int age = 25;
final double PI = 3.14159;
age = 26;
System.out.println(age);
System.out.println(PI);
}
}Output
26
3.14159Interview Tips
- Do not describe a literal as a memory location.
- Clearly distinguish a literal value from the variable that stores it.
- Mention that final prevents reassignment but does not automatically make an object immutable.
Summary
A literal is a value written directly in Java code. Variables store values that may change, while constants are final variables that cannot be reassigned.
Interview Answer
Java provides integer, floating-point, character, string, boolean, and null literals. Each literal type represents a specific kind of value and follows its own syntax rules. Java text blocks are also a multiline form of string literal.
Key Points
- Integer literals represent whole numbers.
- Floating-point literals represent decimal numbers.
- Character literals represent a single Unicode character.
- String literals represent sequences of characters.
- Boolean literals are true and false.
- The null literal represents the absence of an object reference.
Example
public class LiteralTypes {
public static void main(String[] args) {
int integerLiteral = 100;
double floatingLiteral = 25.75;
char characterLiteral = 'J';
String stringLiteral = "Java";
boolean booleanLiteral = true;
String nullReference = null;
System.out.println(integerLiteral);
System.out.println(floatingLiteral);
System.out.println(characterLiteral);
System.out.println(stringLiteral);
System.out.println(booleanLiteral);
System.out.println(nullReference);
}
}Output
100
25.75
J
Java
true
nullInterview Tips
- Remember that null can only be assigned to reference types.
- Do not place true or false inside quotation marks when using boolean literals.
- Character literals use single quotes, while string literals use double quotes.
Summary
Java supports six main literal categories: integer, floating-point, character, string, boolean, and null. The syntax of a literal determines its type and how Java interprets it.
Interview Answer
Integer literals are fixed whole-number values written directly in Java code without a decimal point. Java supports decimal, binary, octal, and hexadecimal representations. Prefixes are used to identify every number system except decimal.
Key Points
- Decimal literals use base 10 and have no prefix.
- Binary literals use base 2 and begin with 0b or 0B.
- Octal literals use base 8 and begin with 0.
- Hexadecimal literals use base 16 and begin with 0x or 0X.
- Integer literals can use the L suffix to represent long values.
- Underscores may improve readability when placed between digits.
Syntax
int decimalValue = 25;
int binaryValue = 0b11001;
int octalValue = 031;
int hexadecimalValue = 0x19;
long longValue = 25L;Example
public class IntegerLiteralExample {
public static void main(String[] args) {
int decimalValue = 25;
int binaryValue = 0b11001;
int octalValue = 031;
int hexadecimalValue = 0x19;
System.out.println(decimalValue);
System.out.println(binaryValue);
System.out.println(octalValue);
System.out.println(hexadecimalValue);
}
}Output
25
25
25
25Interview Tips
- Explain the prefix used by each number system.
- Remember that a leading zero makes an integer literal octal.
- Avoid using digits 8 and 9 in octal literals because they are invalid.
- Prefer uppercase L because lowercase l can look like the digit 1.
Summary
Integer literals represent whole numbers and can be written using decimal, binary, octal, or hexadecimal notation. Although their source representations differ, they can represent the same numeric value.
Interview Answer
Java converts decimal, binary, octal, and hexadecimal literals into binary values during compilation. The prefix tells the compiler which number system should be used to interpret the digits. The number system affects only how the value is written, not how it is stored at runtime.
Key Points
- Decimal literals contain digits from 0 to 9.
- Binary literals contain only 0 and 1.
- Octal literals contain digits from 0 to 7.
- Hexadecimal literals contain digits from 0 to 9 and letters A to F.
- All integer values are ultimately stored in binary form.
- Different literal formats can represent the same value.
Example
public class NumberSystemDemo {
public static void main(String[] args) {
int decimal = 10;
int binary = 0b1010;
int octal = 012;
int hexadecimal = 0xA;
System.out.println(decimal == binary);
System.out.println(binary == octal);
System.out.println(octal == hexadecimal);
}
}Output
true
true
trueInterview Tips
- State that number-system prefixes are compile-time syntax.
- Explain that Java does not store decimal or hexadecimal forms separately.
- Be careful with leading zeros because 010 represents octal 8, not decimal 10.
- Mention that hexadecimal is commonly used for bit masks, colors, and low-level values.
Summary
The compiler interprets integer literals according to their prefixes and converts them into binary values. Decimal, binary, octal, and hexadecimal are different source-code representations of integer values.
Interview Answer
The default type of a normal integer literal in Java is int. To explicitly create a long literal, the value must use the L or l suffix. A decimal literal that exceeds the int range causes a compilation error unless it has the long suffix and fits within the long range.
Key Points
- Unsuffixed decimal integer literals are normally of type int.
- The uppercase L suffix creates a long literal.
- An int occupies 32 bits and a long occupies 64 bits.
- A decimal value outside the int range requires the L suffix.
- The literal must still fit within the long range.
- Hexadecimal, octal, and binary literals have special rules for representing bit patterns.
Syntax
int intValue = 100;
long longValue = 100L;
long largeValue = 3_000_000_000L;Example
public class IntegerLiteralType {
public static void main(String[] args) {
int count = 100;
long population = 8_000_000_000L;
System.out.println(count);
System.out.println(population);
}
}Output
100
8000000000Interview Tips
- Give int as the expected answer when asked for the default integer-literal type.
- Add that L is required when a decimal literal exceeds the int range.
- Use uppercase L in production code for better readability.
- Do not confuse a long variable with a long literal; the literal itself may require the suffix before assignment.
Summary
An integer literal is int by default. Use the L suffix when the literal must be treated as long, especially when its decimal value exceeds the int range.
Interview Answer
The L or l suffix tells the Java compiler to treat an integer literal as a long value instead of an int. It is required when a decimal integer literal exceeds the int range but still fits within the long range. Uppercase L is preferred because lowercase l can be confused with the digit 1.
Key Points
- Integer literals are int by default.
- L and l both create a long literal.
- The suffix is required for large decimal values outside the int range.
- The suffix is optional when an int-range value is assigned to a long variable.
- The literal must fit within the long range.
- Uppercase L improves code readability.
Syntax
long population = 8_000_000_000L;
long count = 100L;Example
public class LongLiteralExample {
public static void main(String[] args) {
long smallValue = 100L;
long largeValue = 5_000_000_000L;
System.out.println(smallValue);
System.out.println(largeValue);
}
}Output
100
5000000000Interview Tips
- State that L changes the literal’s type, not the variable’s type.
- Mention that 5_000_000_000 without L causes a compilation error.
- Prefer uppercase L in production code.
- Do not use the suffix when the value must remain an int.
Summary
Use the L suffix when an integer literal must be treated as long. It is especially necessary when a decimal value exceeds the int range.
Interview Answer
Floating-point literals represent numbers with fractional parts or exponential notation, such as 10.5 or 2.5e3. By default, a floating-point literal is treated as a double. The F or f suffix is required to create a float literal, while D or d can explicitly identify a double literal.
Key Points
- Floating-point literals represent decimal values.
- Their default type is double.
- F or f creates a float literal.
- D or d explicitly creates a double literal.
- Scientific notation can use e or E.
- Floating-point values may contain binary precision errors.
Syntax
double price = 99.99;
float rate = 7.5F;
double scientificValue = 2.5e3;Example
public class FloatingLiteralExample {
public static void main(String[] args) {
double price = 125.75;
float discount = 10.5F;
double scientificValue = 3.2E2;
System.out.println(price);
System.out.println(discount);
System.out.println(scientificValue);
}
}Output
125.75
10.5
320.0Interview Tips
- Give double as the default type of a decimal literal.
- Mention that exponential notation is also a floating-point literal.
- Do not use float or double for exact financial calculations.
- Use BigDecimal when exact decimal precision is required.
Summary
Floating-point literals represent fractional or exponential numeric values. Java treats them as double by default unless the F or f suffix is used.
Interview Answer
A float literal uses the F or f suffix and is stored as a 32-bit single-precision value. A double literal is stored as a 64-bit double-precision value and is the default type for decimal literals. Double provides greater range and precision, while float uses less memory.
Key Points
- Float uses 32 bits.
- Double uses 64 bits.
- Float provides approximately 6 to 7 decimal digits of precision.
- Double provides approximately 15 to 16 decimal digits of precision.
- Float literals require the F or f suffix.
- Double literals need no suffix, but D or d may be used.
- Double is generally preferred for decimal calculations.
Syntax
float floatValue = 12.75F;
double doubleValue = 12.75;
double explicitDouble = 12.75D;Example
public class FloatDoubleExample {
public static void main(String[] args) {
float floatValue = 1.23456789F;
double doubleValue = 1.23456789;
System.out.println(floatValue);
System.out.println(doubleValue);
}
}Output
1.2345679
1.23456789Interview Tips
- Compare float and double using size, precision, and suffix.
- Mention that double is the default floating-point type.
- Explain that both types use IEEE 754 representation.
- Avoid claiming that either type stores all decimal values exactly.
Summary
Float uses less memory but provides lower precision. Double offers greater precision and is the default choice for floating-point literals in Java.
Interview Answer
A decimal literal is treated as a double by default in Java. Assigning a double value to a float variable is a narrowing conversion that may lose precision, so Java does not perform it automatically. The F or f suffix tells the compiler that the literal is already a float.
Key Points
- Decimal literals are double by default.
- Double has a wider range and greater precision than float.
- Double-to-float assignment is a narrowing conversion.
- Java prevents implicit narrowing to avoid accidental data loss.
- The F or f suffix creates a float literal directly.
- An explicit cast can also compile but may hide precision loss.
Syntax
float validValue = 10.5F;
float castValue = (float) 10.5;Example
public class FloatSuffixExample {
public static void main(String[] args) {
float interestRate = 7.25F;
float convertedRate = (float) 8.75;
System.out.println(interestRate);
System.out.println(convertedRate);
}
}Output
7.25
8.75Interview Tips
- Explain that the error occurs because the literal is double, not because it contains a decimal point alone.
- Prefer the F suffix instead of casting a constant decimal value.
- Mention that a cast permits possible precision loss.
- Remember that float value = 10.5 does not compile.
Summary
The F suffix is required because Java treats decimal literals as double by default. It prevents an implicit narrowing conversion from double to float.
Interview Answer
A character literal represents one UTF-16 code unit and is enclosed in single quotation marks. It can contain a normal character, an escape sequence, or a Unicode escape. Java uses the char data type to store character literals.
Key Points
- Character literals use single quotes.
- A char occupies 16 bits.
- A literal normally contains one character.
- Escape sequences represent special characters.
- Unicode escapes use the form backslash-u followed by four hexadecimal digits.
- Character literals store numeric UTF-16 values internally.
- Some Unicode characters require a surrogate pair and cannot fit in one char.
Syntax
char letter = 'A';
char newline = '\n';
char tab = '\t';
char unicodeCharacter = '\u0041';Example
public class CharacterLiteralExample {
public static void main(String[] args) {
char letter = 'J';
char digit = '7';
char newline = '\n';
char unicodeLetter = '\u0041';
System.out.println(letter);
System.out.println(digit);
System.out.print(newline);
System.out.println(unicodeLetter);
}
}Output
J
7
AInterview Tips
- Distinguish 'A' from "A"; the first is char and the second is String.
- Mention that char stores a numeric UTF-16 code unit.
- Do not confuse the character '7' with the integer 7.
- Remember that an empty character literal is invalid.
Summary
Character literals represent individual UTF-16 code units and use single quotation marks. They can be written as normal characters, escape sequences, or Unicode escapes.
Interview Answer
Escape sequences are special character combinations used inside character and string literals to represent characters that are difficult to type directly. Each escape sequence begins with a backslash. Java uses them for line breaks, tabs, quotation marks, backslashes, and other special characters.
Key Points
- Escape sequences begin with a backslash.
- They can be used in char and String literals.
- \n represents a new line.
- \t represents a horizontal tab.
- \ represents a backslash.
- ' represents a single quote.
- " represents a double quote.
- \b, \r, and \f represent backspace, carriage return, and form feed.
Syntax
char newLine = '\n';
char tab = '\t';
char backslash = '\';
String message = "Java\nProgramming";Example
public class EscapeSequenceExample {
public static void main(String[] args) {
System.out.println("Name:\tDattatray");
System.out.println("Java\nProgramming");
System.out.println("Path: C:\Java\Projects");
System.out.println("He said, \"Learn Java\"");
}
}Output
Name: Dattatray
Java
Programming
Path: C:\Java\Projects
He said, "Learn Java"Interview Tips
- Remember that a backslash must be escaped as \.
- Use " inside a string containing double quotes.
- Do not confuse \n with the characters '' and 'n'.
- Mention that escape sequences are interpreted by the compiler.
Summary
Escape sequences represent special characters inside Java literals. Common examples include \n, \t, \, ', and ".
Interview Answer
Unicode character literals represent characters using Unicode escape notation. They are written using backslash-u followed by exactly four hexadecimal digits. Java processes Unicode escapes before normal tokenization, so they can appear in character literals, strings, and even other parts of the source code.
Key Points
- Unicode escapes use the format backslash-u followed by four hex digits.
- The four characters after backslash-u must be hexadecimal digits.
- Java char stores one UTF-16 code unit.
- Unicode escapes can represent letters, symbols, and special characters.
- Some characters outside the Basic Multilingual Plane require two char values.
- Unicode escapes are processed early during compilation.
Syntax
char letter = '\u0041';
char rupeeSymbol = '\u20B9';Example
public class UnicodeLiteralExample {
public static void main(String[] args) {
char capitalA = '\u0041';
char rupeeSymbol = '\u20B9';
char omega = '\u03A9';
System.out.println(capitalA);
System.out.println(rupeeSymbol);
System.out.println(omega);
}
}Output
A
₹
ΩInterview Tips
- State that Unicode escapes require exactly four hexadecimal digits.
- Mention that one char represents one UTF-16 code unit, not always one complete Unicode character.
- Do not assume every Unicode symbol fits into a single char.
- Be aware that Unicode escapes are processed before regular Java syntax.
Summary
Unicode character literals use backslash-u notation to represent UTF-16 code units. They allow Java source code to represent characters independently of the keyboard or file encoding.
Interview Answer
A string literal is a sequence of characters enclosed in double quotation marks. Java stores string literals in a special memory area called the String Pool so identical literals can share the same String object. This reduces duplicate object creation and improves memory efficiency.
Key Points
- String literals use double quotation marks.
- String objects are immutable.
- Identical string literals usually refer to the same pooled object.
- The String Pool is maintained by the JVM.
- The new keyword creates a separate String object.
- The intern() method returns the pooled representation of a string.
- Use equals() to compare string content.
Example
public class StringPoolExample {
public static void main(String[] args) {
String first = "Java";
String second = "Java";
String third = new String("Java");
System.out.println(first == second);
System.out.println(first == third);
System.out.println(first.equals(third));
System.out.println(first == third.intern());
}
}Output
true
false
true
trueInterview Tips
- Explain that == compares references, while equals() compares content.
- Mention that identical literals share a pooled object.
- Do not say that every String object is automatically stored in the pool.
- Explain that new String("Java") creates a separate object.
Summary
String literals are immutable sequences of characters stored in the String Pool. Identical literals can share one object, but strings created with new usually create separate objects.
Interview Answer
Java provides two boolean literals: true and false. They can only be assigned to boolean variables or used in logical conditions. The null literal represents the absence of an object reference and can only be assigned to reference types.
Key Points
- true and false are the only boolean literals.
- Boolean literals are not numeric values.
- They are commonly used in conditions and logical expressions.
- null can be assigned to objects, arrays, interfaces, and wrapper types.
- null cannot be assigned to primitive data types.
- Accessing an instance member through null causes NullPointerException.
- A null reference does not point to any object.
Syntax
boolean active = true;
boolean completed = false;
String name = null;
Integer count = null;Example
public class BooleanNullExample {
public static void main(String[] args) {
boolean loggedIn = true;
String userName = null;
if (loggedIn) {
System.out.println("User is logged in");
}
System.out.println(userName == null);
}
}Output
User is logged in
trueInterview Tips
- Do not compare a boolean with 0 or 1 in Java.
- State that null is a literal, not a keyword representing an object.
- Mention that primitives cannot store null.
- Explain that unboxing a null wrapper causes NullPointerException.
Summary
Boolean literals represent logical truth values, while null represents the absence of an object reference. Boolean literals work with boolean expressions, and null works only with reference types.
Interview Answer
Common mistakes include forgetting numeric suffixes, exceeding type ranges, using invalid digits in binary or octal literals, placing underscores incorrectly, and assuming floating-point values are exact. These issues can cause compilation errors, overflow, precision loss, or unexpected values. Developers should understand literal syntax, range limits, and default data types.
Key Points
- Large integer literals require the L suffix.
- Float literals require the F suffix.
- Lowercase l can be confused with the digit 1.
- Octal literals cannot contain digits 8 or 9.
- Binary literals can contain only 0 and 1.
- Underscores cannot appear at the beginning or end of a literal.
- Underscores cannot be placed next to a decimal point or suffix.
- Narrowing casts can cause overflow or precision loss.
- Float and double values may not represent decimal values exactly.
Example
public class LiteralMistakes {
public static void main(String[] args) {
long population = 8_000_000_000L;
float percentage = 75.5F;
int binaryValue = 0b1010;
int hexadecimalValue = 0xFF;
int readableNumber = 1_000_000;
byte narrowedValue = (byte) 130;
System.out.println(population);
System.out.println(percentage);
System.out.println(binaryValue);
System.out.println(hexadecimalValue);
System.out.println(readableNumber);
System.out.println(narrowedValue);
}
}Output
8000000000
75.5
10
255
1000000
-126Interview Tips
- Check the destination type’s range before assignment or casting.
- Use uppercase L and F suffixes for readability.
- Be careful with leading zeros because they create octal literals.
- Use BigDecimal for exact decimal calculations.
- Remember that underscores improve readability but do not change the value.
Summary
Literal-related mistakes usually come from incorrect suffixes, invalid formats, range overflow, and precision assumptions. Proper syntax and type selection help prevent compilation errors and unexpected results.