Published: 31 Jan 2025 | Reading Time: 4 min read
Literals in Java were introduced as part of the core language when Java was created in 1995 by Sun Microsystems (now Oracle). Java was designed to be a simple, object-oriented programming language focused on portability and ease of use, and literals played an important role in providing the foundation for specifying values that remain unchanged throughout the program's execution.
Understanding literals in Java is essential because they simplify coding and ensure the clarity of constant values. This article will explore the different types of literal templates in Java and how to use them effectively in Java programs.
Literals in Java are constant values that are assigned directly to variables. A literal can be a number, a character, a string, or any other predefined value. These fixed values are used to initialize variables or define the code's constant expressions.
Literals are important in Java for several reasons:
int x = 10; // 10 is an integer literal
String name = "John"; // "John" is a string literal
Java supports several types of literals, each used to represent different types of data. Let's take a closer look at the common literal types in Java.
Integer literals represent whole numbers and can be written in various number systems, including decimal, binary, octal, and hexadecimal.
Number Systems:
0b or 0B00x or 0Xint decimal = 100; // Decimal literal
int binary = 0b1010; // Binary literal
int octal = 077; // Octal literal
int hexadecimal = 0x2A; // Hexadecimal literal
public class Main {
public static void main(String[] args) {
int num1 = 100; // Integer literal
double num2 = 99.99; // Floating-point literal
System.out.println(num1 + num2); // Outputs: 199.99
}
}
Explanation: This example demonstrates how integer (100) and floating-point (99.99) literals can be used in arithmetic operations to produce a result (199.99).
Floating-point literals represent decimal numbers (i.e., numbers with a fractional part). In Java, there are two types of floating-point literals:
f or F suffixfloat pi = 3.14f; // Float literal
double e = 2.71828; // Double literal
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
char letter = 'J';
System.out.println(greeting + " " + letter);
}
}
Output:
Hello J
Explanation: This example shows the combination of a string literal ("Hello") and a character literal ('J') to construct and print a greeting message.
A character literal represents a single character enclosed in single quotes. It can also include escape sequences to represent special characters.
For char data types, we can specify literals in 4 ways:
In Java, a single quote is used to denote character literals. A character literal represents a single character enclosed within single quotes (' '), such as 'A' or '7'. It is a primitive data type of char, which stores a single 16-bit Unicode character.
A char literal in Java can also be treated as an integral literal because the char data type is internally represented as an unsigned 16-bit integer (ranging from 0 to 65535). When a character is used in expressions, it is often treated as its corresponding numeric Unicode value.
In Java, each character is internally represented using Unicode. Unicode escape sequences allow you to specify characters using their Unicode values, represented in the form of \u followed by a four-digit hexadecimal number.
An escape sequence in Java is a combination of characters representing a special character or action. These are used when inserting characters with special meanings (like newlines, tabs, or quotes) or are not easily typed directly.
Common Escape Sequences:
\n: Newline\t: Tab\\: Backslash\': Single quote\": Double quote\r: Carriage return\b: Backspacechar letter = 'A'; // Character literal
char newline = '\n'; // Escape sequence for newline
char letter = '\u0041'; // Unicode for 'A'
System.out.println("Hello\nWorld!"); // Outputs:
// Hello
// World!
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
if (isJavaFun) {
System.out.println("Java is fun!");
}
}
}
Output:
Java is fun!
Explanation: This example uses the boolean literal true to control the flow of execution in a conditional statement, printing "Java is fun!" if the condition is met.
A string literal represents a sequence of characters enclosed in "double quotes". In Java, string literals are objects of the String class, and they are automatically stored in the string pool for memory optimisation.
public class Main {
public static void main(String[] args) {
// Example 1: Concatenating string literals
String greeting = "Hello, World!\n" +
"Welcome to Java programming.\n" +
"Let's learn about string literals!";
System.out.println(greeting);
}
}
Output:
Hello, World!
Welcome to Java programming.
Let's learn about string literals!
Explanation: The above example allows you to easily create multi-line string literals without needing explicit newline characters (\n). The string literal spans multiple lines within triple quotes ("""), and the JVM stores it in the string pool for memory optimisation.
Boolean literals represent truth values, with only two possible values: true and false. These literals are commonly used in conditional statements to control program flow.
boolean isJavaFun = true; // Boolean literal
The null literal represents the absence of a value. It can be assigned to object references but not to primitive data types.
String name = null; // Null literal
In Java, a class literal refers to the class type itself, represented by the class name followed by .class. This refers to the Class object associated with the class in the Java runtime environment.
public class ClassLiteralsExample {
public static void main(String[] args) {
// Using a class literal
Class<String> stringClass = String.class;
System.out.println("Class Name: " + stringClass.getName());
// Another example with Integer class
Class<Integer> integerClass = Integer.class;
System.out.println("Class Name: " + integerClass.getName());
}
}
Output:
Class Name: java.lang.String
Class Name: java.lang.Integer
Explanation: This code demonstrates how to use class literals in Java. It creates Class objects for String.class and Integer.class, then prints their full class names using the getName() method. Class literals are helpful in reflection and runtime class inspections.
An integer literal in Java should only contain digits, and if it has a decimal point or any non-numeric character, it's invalid.
int invalidbinary = 0b123; // Error: Invalid binary number
Output:
class java.lang.String
The Java template literals aren't directly supported in the way they are in JavaScript. However, Java provides powerful string formatting mechanisms like String.format() and string concatenation for dynamically constructing strings.
In JavaScript, template literals allow for easy interpolation of variables within strings using backticks () and ${}syntax. At the same time, Java uses methods likeString.format()` or concatenation with the '+' operator to format strings.
// Using String.format()
String formattedString = String.format("Hello, %s!", "World");
// Using concatenation
String greeting = "Hello, " + "World!";
In Java, the performance of string initialisation can differ significantly between using string literals and creating new string objects.
When a string is initialised with a literal, like String s1 = "Nxtwave"; Java checks its string pool (also known as the intern pool). Suppose the string already exists in the pool. In that case, it simply references the existing object, ensuring that only one instance of the string is created, even if it is used multiple times throughout the program. This is efficient because it reduces memory usage and enhances performance by avoiding unnecessary object creation.
While String Object uses new String("Nxtwave"), Java forces the creation of a new string object on the heap, even if the string already exists in the string pool. This is less efficient because it involves allocating new memory for each string object created, leading to increased time and memory consumption.
Here is the comparison between string literal and string objects in Java:
| Aspect | String Literal | String Object |
|---|---|---|
| Storage Location | Stored in the String Pool (intern pool) | A new object is created in heap memory |
| Object Reuse | Reuses the existing object if the value "Nxtwave" exists in the pool | Creates a new object in memory even if "Nxtwave" exists in the pool |
| Syntax | String name = "Nxtwave"; |
String name = new String("Nxtwave"); |
| Performance | Faster because it uses the string pool and avoids duplicate objects | Slower because a new object is created every time |
| Memory Efficiency | Efficient in memory usage as it avoids duplicate objects | Less efficient as each string object takes up memory on the heap |
| Interning | Implicitly interns the string (uses string pool) | Does not intern automatically unless explicitly called using intern() |
| Reference Comparison | Both name1 and name2 referring to "Nxtwave" would point to the same object in memory | Even if the values are the same, name1 and name2 are different objects in memory |
| Garbage Collection | Objects in the string pool are not garbage collected | Objects created with new String() are subject to garbage collection once they're no longer referenced |
class StringExample {
public static void main(String args[]) {
// String literal
String name1 = "Nxtwave";
String name2 = "Nxtwave";
// String object
String name3 = new String("Nxtwave");
String name4 = new String("Nxtwave");
System.out.println(name1 == name2); // true, as both reference the same object in the pool
System.out.println(name1 == name3); // false, as name3 is a new object
System.out.println(name3 == name4); // false, both are new objects with the same value
}
}
Output:
true
false
false
Explanation:
name1 == name2: Both are string literals referring to same object in the string pool, so it returns truename1 == name3: name1 is a literal, and name3 is a new object. They are different, so it returns falsename3 == name4: Both name3 and name4 are new objects with the same value but different objects in memory, so it returns falseHere are the common errors while using literals in Java:
int x = 3.14;char ch = "A"; (which should be a char)float num = 5.0;int num = 0b12; (which is invalid)String text = null; text.length();, which causes a NullPointerExceptionBy using the JDK 7 feature allows underscores in numeric literals for better readability. Here are some rules to understand the proper usage and restrictions of underscores in Java numeric literals.
You can't put underscores before or after an integer.
Example:
int p = _10; or int p = 10_; is invalid.
You cannot place underscores directly next to a decimal point in floating-point numbers.
Example:
float a = 10._0f; or float a = 10_.0f; is invalid.
You can't use an underscore before the L suffix for long literals or the F suffix for floating-point literals.
Example:
long a = 10_100_00_L; or float a = 10_100_00_F; is invalid.
Example:
int a = 1__000;
would be invalid due to multiple consecutive underscores.
You can use underscores to improve the readability of large numbers, such as in constants or large literals.
int largeNumber = 1_000_000; // Easy to read 1 million
long creditCardNumber = 1234_5678_9012_3456L; // Makes it easier to read the number
When using hexadecimal, underscores can be used to separate groups of digits for better readability.
int hexValue = 0x1A_FF_9B; // Valid hexadecimal literal with underscores
In binary literals, underscores can also improve readability.
int binaryValue = 0b1101_1010; // Valid binary literal with underscores
Underscores can be used in floating-point literals as well, which can be especially useful for separating digits in large decimal numbers.
double pi = 3.141_592_653_589_793; // Pi value
double largeDecimal = 123_456_789.987_654_321;
You cannot use an underscore at the start or end of a numeric literal.
int invalid1 = _1000; // Invalid
int invalid2 = 1000_; // Invalid
You cannot place an underscore next to the decimal point in floating-point literals.
float invalid = 3.14_15f; // Invalid
You cannot use underscores immediately after the 0X, 0B, or 0 prefix.
int invalidHex = 0X_1A; // Invalid
int invalidBinary = 0B_1010; // Invalid
You cannot use multiple consecutive underscores within a numeric literal.
int invalid = 1__000; // Invalid
public class Example {
public static void main(String[] args) {
// Underscore in integral literal (int)
int a = 7_7;
System.out.println("The value of a is = " + a);
double p = 11.239_67_45;
System.out.println("The value of p is = " + p);
float q = 16.45_56f;
System.out.println("The value of q is = " + q);
int c = 0B01_01;
System.out.println("c = " + c);
int d = 0x2_2;
System.out.println("d = " + d);
int e = 02_3;
System.out.println("e = " + e);
}
}
Output:
The value of a is = 77
The value of p is = 11.2396745
The value of q is = 16.4556
c = 5
d = 34
e = 19
Explanation:
In conclusion, literals in Java play a crucial role in representing fixed values such as numbers, characters, strings, booleans, and null references within a program. They allow developers to define constants and assign values directly to variables. Understanding the different types of literals, such as integer, floating-point, character, string, boolean, and null literals, is essential for efficient and error-free coding. By avoiding common mistakes, such as range issues, invalid escape sequences, and null reference errors, developers can write cleaner and more optimised Java programs. Proper usage of literals ensures robust and maintainable code.
A literal is a specific value assigned directly to a variable or used in expressions. For example, the number 10 or a string "Hello" are literals because they represent fixed values of particular data types.
Example:
int age = 25; // 25 is an integer literal
double price = 19.99; // 19.99 is a double literal
char grade = 'A'; // 'A' is a char literal
boolean isJavaFun = true; // true is a boolean literal
String name = "Nxtwave"; // "Nxtwave" is a string literal
A literal data type refers to the specific type of value that a literal represents. In Java, literals can be categorized according to the data type they represent:
i) Integer literals: Represent whole numbers.
Example: int num = 100; (100 is an integer literal)
ii) Floating-point literals: Represent numbers with decimal points.
Example: double price = 19.99; (19.99 is a double literal)
iii) Character literals: Represent a single character.
Example: char letter = 'A'; ('A' is a character literal)
iv) String literals: Represent a sequence of characters.
Example: String greeting = "Hello, World!"; ("Hello, World!" is a string literal)
v) Boolean literals: Represent a true or false value.
Example: boolean isActive = true; (true is a boolean literal)
i) Identifiers
An identifier in Java is the name given to various program elements such as variables, methods, classes, and other user-defined items.
An identifier must begin with a letter (A-Z or a-z), a dollar sign ($), or an underscore (_), and can be followed by letters, digits (0-9), dollar signs, or underscores.
Identifiers are case-sensitive, meaning variables and Variables are different.
Example:
int age = 25; // 'age' is an identifier for the variable
ii) Literals
As mentioned earlier, literals are constant values directly used in the code to represent specific data types.
Examples include numeric values (like 100), strings (like "Java"), and boolean values (true or false).
Example:
String language = "Java"; // "Java" is a literal
Related Articles: