Types of Literals in Java
Java supports many literals, each somehow connected to a specific data type. The main types of literals in Java are:
1. Integer Literals:
- Integer literals are used to represent whole numbers.
- They can be positive, negative, or zero.
- Examples: 42, -10, 0
2. Character Literals:
- Character literals represent single characters.
- They are enclosed in single quotes (' ').
- Examples: 'a', 'Z', '5'
3. Boolean Literals:
- Boolean literals represent logical values.
- There are only two boolean literals: true & false.
- Examples: true, false
4. String Literals:
- String literals represent a sequence of characters.
- They are enclosed in double quotes (" ").
- Examples: "Hello", "Java Programming", "123"
5. Floating-Point Literals:
- Floating-point literals represent decimal numbers.
- They can have a fractional part & an optional exponent.
- Examples: 3.14, -2.5, 1.0e-3
Integer Literal
Integer literals are used to represent whole numbers in Java. They can be positive, negative, or zero. Integer literals can be written in three different number systems: decimal, octal, and hexadecimal.
1. Decimal Literals:
- Decimal literals are the most common form of integer literals.
- They consist of digits from 0 to 9.
- Examples: 42, -10, 0
2. Octal Literals:
- Octal literals start with a leading zero (0) followed by digits from 0 to 7.
- They represent numbers in the base-8 number system.
- Examples: 052 (equivalent to decimal 42), 0123 (equivalent to decimal 83)
3. Hexadecimal Literals:
- Hexadecimal literals start with a leading 0x or 0X followed by digits from 0 to 9 and letters from A to F (case-insensitive).
- They represent numbers in the base-16 number system.
- Examples: 0x2A (equivalent to decimal 42), 0xAF (equivalent to decimal 175)
For example:
int decimalLiteral = 42;
int octalLiteral = 052;
int hexadecimalLiteral = 0x2A;
System.out.println(decimalLiteral); // Output: 42
System.out.println(octalLiteral); // Output: 42
System.out.println(hexadecimalLiteral); // Output: 42
In the above code, we assign integer literals in different number systems to variables of type int. The output shows that all three literals represent the same value, which is 42 in decimal.
Character Literal
Character literals in Java represent single characters. They are enclosed in single quotes (' ') and can include letters, digits, punctuation marks, and other symbols. In Java, character literals are of type char.
Let’s look at a few examples of character literals:
char ch1 = 'a';
char ch2 = 'Z';
char ch3 = '5';
char ch4 = '$';
In the above code, each character literal is assigned to a variable of type char.
Java also supports special character literals, known as escape sequences, which represent non-printable characters or characters with special meaning. Some commonly used escape sequences are:
- '\n': Newline character
- '\t': Tab character
- '\\': Backslash character
- '\'': Single quote character
- '\"': Double quote character
For example:
public class EscapeCharacterDemo {
public static void main(String[] args) {
char newline = '\n';
char tab = '\t';
char singleQuote = '\'';
System.out.println("First line" + newline + "Second line");
System.out.println("Name" + tab + "Age");
System.out.println("I'm using single quotes: " + singleQuote);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
First line
Second line
Name Age
I'm using single quotes: '
In the above code, we use escape sequences to include special characters in the output. The newline escape sequence ('\n') is used to move to a new line, the tab escape sequence ('\t') is used to insert a tab space, & the single quote escape sequence ('\'') is used to include a single quote character within a string.
Boolean Literal
Boolean literals in Java represent logical values & can have only two possible values: true or false. They are used to represent the truth or falsity of a condition or statement.
Let’s discuss few examples of boolean literals:
boolean isTrue = true;
boolean isFalse = false;
In the above code, we assign the boolean literals true & false to variables of type boolean.
Boolean literals are commonly used in conditional statements, such as if statements or while loops, to control the flow of program execution based on certain conditions.
For example:
public class CheckAdult {
public static void main(String[] args) {
int age = 20;
boolean isAdult = age >= 18;
if (isAdult) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not an adult.");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
You are an adult.
In the above code, we assign the boolean literal true to the isAdult variable if the age is greater than or equal to 18. The if statement checks the value of isAdult & executes the corresponding block of code based on its value.
Boolean literals are also used in logical expressions and operators, such as && (logical AND), || (logical OR), and &! (logical NOT), to perform logical operations and make decisions based on multiple conditions.
Let’s look at an example that shows the use of boolean literals with logical operators:
public class DiscountCheck {
public static void main(String[] args) {
boolean isStudent = true;
boolean isDiscountAvailable = false;
if (isStudent && isDiscountAvailable) {
System.out.println("You are eligible for a student discount.");
} else {
System.out.println("You are not eligible for a student discount.");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
You are not eligible for a student discount.
In the above code, we use the && (logical AND) operator to check if both isStudent and isDiscountAvailable are true. Since isDiscountAvailable is false, the condition evaluates to false, and the else block is executed.
String Literal
String literals in Java represent a sequence of characters enclosed in double quotes (" "). They are used to store & manipulate text values in a program. String literals are of type String in Java.
A few examples of string literals are:
String message = "Hello, World!";
String name = "Rashmi Sharma";
String emptyString = "";
In the above code, we assign string literals to variables of type String. The message variable holds the value "Hello, World!" and the name variable holds the value "Rashmi Sharma", & the emptyString variable holds an empty string.
String literals can include letters, digits, spaces, punctuation marks, & special characters. They can also span multiple lines by using the newline escape sequence ('\n').
For example:
public class GreetingMessage {
public static void main(String[] args) {
String greeting = "Hello";
String name = "Priya";
String message = greeting + ", " + name + "!";
System.out.println(message);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Hello, Priya!
In the above code, we concatenate multiple string literals using the + operator to create a new string. The resulting string, "Hello, Priya!", is then printed to the console.
Java also provides various methods in the String class to manipulate & process string literals. Some commonly used methods are:
- length(): Returns the length of the string.
- toUpperCase(): Converts the string to uppercase.
- toLowerCase(): Converts the string to lowercase.
- substring(int beginIndex, int endIndex): Extracts a substring from the string.
- equals(Object obj): Compares the string with another object for equality.
For example:
public class StringManipulation {
public static void main(String[] args) {
String text = "Hello, World!";
int length = text.length();
String upperCase = text.toUpperCase();
String lowerCase = text.toLowerCase();
String substring = text.substring(7, 12);
System.out.println("Length: " + length);
System.out.println("Uppercase: " + upperCase);
System.out.println("Lowercase: " + lowerCase);
System.out.println("Substring: " + substring);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Length: 13
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Substring: World
In the above code, we apply various string methods to the text variable and print the results. The length() method returns the length of the string, toUpperCase() converts the string to uppercase, toLowerCase() converts the string to lowercase, and substring(7, 12) extracts the substring "World" from the original string.
Floating Point Literals
Floating-point literals in Java represent decimal numbers with a fractional part. They can be used to store and manipulate real numbers in a program. Java supports two types of floating-point literals: float and double.
1. float Literals:
- float literals are used to represent single-precision floating-point numbers.
- They are specified by appending the letter 'f' or 'F' to the number.
- Examples: 3.14f, -2.5F, 1.0f
2. double Literals:
- double literals are used to represent double-precision floating-point numbers.
- They are the default type for floating-point literals in Java.
- Examples: 3.14, -2.5, 1.0
Let’s look at a few examples of floating-point literals:
float pi = 3.14f;
double e = 2.71828;
double negativeValue = -1.5;
float scientificNotation = 1.2e-3f;
In the above code, we assign floating-point literals to variables of type float & double. The pi variable holds the value 3.14 as a float, the e variable holds the value 2.71828 as a double, the negativeValue variable holds the value -1.5 as a double, & the scientificNotation variable holds the value 1.2 x 10^-3 as a float using scientific notation.
Floating-point literals can also be written in scientific notation using the letter 'e' or 'E' followed by an exponent. For example, 1.2e-3 represents 1.2 x 10^-3, which is equivalent to 0.0012.
It's important to note that floating-point numbers are approximate representations & may have precision limitations. Due to the binary nature of floating-point arithmetic, certain decimal numbers cannot be represented exactly, leading to small rounding errors.
For example:
public class CircleArea {
public static void main(String[] args) {
double radius = 5.0;
double area = Math.PI * Math.pow(radius, 2);
System.out.println("Area: " + area);
}
}
Output:
Area: 78.53981633974483
In the above code, we calculate the area of a circle using the Math.PI constant (which represents the value of pi) and the Math.pow() method to compute the square of the radius. The result is stored in the area variable and printed to the console.
Invalid Literals
In Java, certain combinations of characters or values are considered invalid literals and will result in a compilation error if used in the code. It's important to be aware of these invalid literals to avoid common mistakes and ensure that your code is syntactically correct.
Some examples of invalid literals in Java are:
1. Integer Literals:
- Leading zeros in decimal literals (except for the value 0 itself)
Example: 0123 (invalid)
- Underscores in illegal positions, such as at the beginning, end, or adjacent to a decimal point
Example: _123, 123_, 1_.23 (invalid)
2. Floating-Point Literals:
- Multiple decimal points in a single literal
Example: 3.14.15 (invalid)
- Underscores in illegal positions, such as at the beginning, end, or adjacent to a decimal point or exponent
Example: _3.14, 3.14_, 3_.14, 3.14_e2 (invalid)
3. Character Literals:
- Empty character literals or character literals with more than one character
Example: '', 'ab' (invalid)
- Unrecognized escape sequences
Example: '\x', '\u12' (invalid)
4. String Literals:
- Unclosed string literals or missing closing double quotes
Example: "Hello, World! (invalid)
- Unescaped newline characters within a string literal
Example: "Hello,
World!" (invalid)
These are a few examples of invalid literals that will give compilation errors:
// Invalid integer literal
int num = 0123;
// Invalid floating-point literal
double pi = 3.14.15;
// Invalid character literal
char ch = 'ab';
// Invalid string literal
String str = "Hello, World!;
In the above code, each of the literals assigned to the variables is invalid & will cause a compilation error.
It's important to follow the proper syntax and rules for literals in Java to ensure that your code is valid and can be compiled successfully. If you encounter a compilation error related to an invalid literal, carefully review the syntax and make the necessary corrections.
Restrictions to Use Underscore (_)
In Java, the underscore character (_) can be used as a separator in numeric literals to improve readability. However, certain restrictions and guidelines must be followed when using underscores in literals.
The key restrictions and rules for using underscores in numeric literals are:
1. Underscores can only be used between digits. They cannot be used at the beginning or end of a literal, adjacent to a decimal point, or adjacent to an exponent.
Valid examples: 1_000_000, 3.14_15, 1.2e3_4
Invalid examples: _1000000, 3_.1415, 1.2_e34
2. Consecutive underscores are not allowed. There must be at least one digit between any two underscores.
Valid example: 1_2_3
Invalid example: 1__23
3. Underscores cannot be used in the binary, octal, or hexadecimal prefixes.
Valid examples: 0b1010_1100, 0123_456, 0x1F_2A
Invalid examples: 0_b1010_1100, 0_123456, 0x_1F2A
4. Underscores cannot be used in the 'l' or 'L' suffix for long literals or the 'f' or 'F' suffix for float literals.
Valid examples: 1000_000L, 3.14_15F
Invalid examples: 1000000_L, 3.1415_F
Let’s look at a few examples of using underscores in numeric literals:
int million = 1_000_000;
long creditCardNumber = 1234_5678_9012_3456L;
double pi = 3.14_15;
float scientificNotation = 1.2e3_4F;
In the above code, underscores are used to separate groups of digits, making the literals more readable. The million variable holds the value 1,000,000, the creditCardNumber variable holds the value 1234567890123456L, the pi variable holds the value 3.1415, & the scientificNotation variable holds the value 1.2 x 10^34.
It's important to use underscores judiciously & follow the restrictions mentioned above to ensure that your code is valid & compiles successfully. The purpose of underscores is to enhance the readability of numeric literals, especially when dealing with large numbers or complex floating-point values.
Why use literals?
1. Direct value representation: Literals allow you to represent values directly in your code without the need for additional variables or calculations. They provide a way to specify exact values that are known at the time of writing the code.
2. Improved code readability: With the help of literals, you can make your code more readable & self-explanatory. Instead of using variables or complex expressions to represent values, literals allow you to express the values directly, making the code easier to understand & maintain.
3. Efficient memory usage: When you use literals in your code, the Java compiler can optimize memory usage by allocating memory for the literal values during compilation. This means that the literals are stored in the constant pool, which is a special area of memory dedicated to storing constant values. By reusing literals from the constant pool, the program can save memory & avoid unnecessary object creation.
4. Compile-time error detection: Using literals helps catch errors during compilation. If you accidentally use an invalid literal or violate the syntax rules for literals, the Java compiler will detect the error and provide a compile-time error message. This early error detection helps identify and fix issues before the program is executed.
5. Simplified expressions: Literals simplify expressions by allowing you to use the actual values directly in calculations, comparisons, or assignments. Instead of creating variables to hold intermediate values, you can use literals to perform operations directly, making the code more concise & easier to understand.
How to use literals?
Using literals in Java is very easy, and we can directly incorporate them into our code. Let’s discuss some guidelines on how to use literals effectively:
1. Assign literals to variables: You can assign literals directly to variables of the appropriate data type. This allows you to store & reuse the literal values throughout your code.
Example:
int age = 25;
double price = 9.99;
String name = "Rahul";
2. Use literals in expressions: Literals can be used directly in expressions, such as arithmetic operations, comparisons, or method arguments. They serve as the actual values in these expressions.
Example:
int sum = 10 + 20;
boolean isAdult = age >= 18;
String message = "Hello, " + name + "!";
3. Use literals in conditional statements: Literals can be used in conditional statements, such as if statements or switch cases, to evaluate conditions or make decisions based on specific values.
Example:
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
4. Use literals as method arguments: When calling methods, you can pass literals directly as arguments. This is useful when you know the exact values to be passed & don't need to store them in variables.
Example:
System.out.println("Hello, World!");
int result = Math.max(10, 20);
5. Use literals in array initialization: Literals can be used to initialize arrays directly with specific values. This is convenient when you know the initial values of an array upfront.
Example:
int[] numbers = {1, 2, 3, 4, 5};
String[] fruits = {"apple", "banana", "orange"};
6. Use literals in switch statements: Literals can be used as case values in switch statements to perform different actions based on specific values.
Example:
int dayNumber = 3;
switch (dayNumber) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
// ...
}
Note: Whenever you are using literals, it's important to choose the appropriate data type that can accommodate the literal value. For example, if you have a large integer value, you might need to use a long literal (e.g., 1000000000L) to avoid integer overflow.
Frequently Asked Questions
What is the difference between integer & floating-point literals?
Integer literals represent whole numbers, while floating-point literals represent numbers with decimal points. Integer literals can be of type int or long, whereas floating-point literals can be of type float or double.
Can underscores be used in all types of literals?
Underscores can be used as separators in integer & floating-point literals to improve readability. However, they cannot be used in character or string literals.
Are literals more efficient than variables?
Literals are often more efficient than variables because they are stored in the constant pool and can be reused, saving memory. Additionally, using literals directly in expressions eliminates the need for extra variables, resulting in more concise and efficient code.
Conclusion
In this article, we discussed the concept of literals in Java and learned about the different types of literals, including integer, character, boolean, string, and floating-point literals. We also discussed the restrictions on using underscores in numeric literals and the importance of using literals effectively. Literals play a crucial role in representing values directly in code, improving readability, optimizing memory usage, and simplifying expressions.
You can also check out our other blogs on Code360.