What Are Literals in Java?
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:
- They provide a simple and clear way to define constants.
- They help in performing operations and comparisons.
- They allow programmers to write clean and concise code.
Example
int x = 10; // 10 is an integer literal
String name = "John"; // "John" is a string literal
Types of Literals in Java
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.
1. Integer Literals
Integer literals represent whole numbers and can be written in various number systems, including decimal, binary, octal, and hexadecimal.
- Decimal: The standard base-10 number system.
- Binary: Numbers in base-2, prefixed with 0b or 0B.
- Octal: Numbers in base-8, prefixed with 0.
- Hexadecimal: Numbers in base-16, prefixed with 0x or 0X.
Example
int decimal = 100; // Decimal literal
int binary = 0b1010; // Binary literal
int octal = 077; // Octal literal
int hexadecimal = 0x2A; // Hexadecimal literal
Program Using Integer and Floating-Point Literals
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
}
}
This example demonstrates how integer (100) and floating-point (99.99) literals can be used in arithmetic operations to produce a result (199.99).
2. Floating-Point Literals
Floating-point literals represent decimal numbers (i.e., numbers with a fractional part). In Java, there are two types of floating-point literals:
- float: Single precision, represented with an f or F suffix.
- double: Double precision, the default type for floating-point literals in Java.
Example
float pi = 3.14f; // Float literal
double e = 2.71828; // Double literal
Program Using String and Character Literals in Action
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.
3. Character Literals or Char Literals
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:
3.1 Single quote
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
3.2 Char literal as Integral literal
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.
3.3 Unicode Representation
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.
3.4 Escape Sequence
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 include:
- \n: Newline
- \t: Tab
- \\: Backslash
- \': Single quote
- \": Double quote
- \r: Carriage return
- \b: Backspace
Example
char 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!
Program Using Boolean Literals in Conditional Statements
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.
4. Java String Literals
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.
Example
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!
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.
5. Boolean Literals
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.
Example
boolean isJavaFun = true; // Boolean literal
6. Null Literal
The null literal represents the absence of a value. It can be assigned to object references but not to primitive data types.
Example
String name = null; // Null literal
7. Class Literals
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.
Example
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
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.
8. Invalid Integer Literals
An integer literal in Java should only contain digits, and if it has a decimal point or any non-numeric character, it's invalid.
Example
int invalidbinary = 0b123; // Error: Invalid binary number
Output
class java.lang.String
Template Literal Java
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 like String.format() or concatenation with the ‘+’ operator to format strings.
Example
// Using String.format()
String formattedString = String.format("Hello, %s!", "World");
// Using concatenation
String greeting = "Hello, " + "World!";
Key Differences Between String Literals and String Objects in Java
In Java, the performance of string initialisation can differ significantly between using string literals and creating new string objects.
String Literal
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.
String Object
While String Object uses a 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.
String Literal Vs String Objects in Java
Here is the comparison between string literal and string objects in Java:
String Literal |
String Object |
Stored in the String Pool (intern pool). |
A new object is created in heap memory. |
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. |
String name = "Nxtwave"; |
String name = new String("Nxtwave"); |
Faster because it uses the string pool and avoids duplicate objects. |
Slower because a new object is created every time. |
Efficient in memory usage as it avoids duplicate objects. |
Less efficient as each string object takes up memory on the heap. |
Implicitly interns the string (uses string pool). |
Does not intern automatically unless explicitly called using intern(). |
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. |
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. |
Example
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
- Both are string literals referring to same object in the string pool, so it returns true.
- name1 is a literal, and name3 is a new object. They are different, so it returns false.
- Both name3 and name4 are new objects with the same value but different objects in memory, so it return false.
Common Errors While Using Literals in Java
Here are the common errors while using literals in Java:
- Mismatched Data Types: Assigning an incompatible literal to a variable, such as int x = 3.14;.
- Improper Character Representation: Using double quotes for characters, like char ch = "A"; (which should be a char).
- Missing Suffix for Floats: Omitting the F suffix for float literals, such as float num = 5.0;.
- Invalid Literals: Using incorrect binary or hexadecimal literals, like int num = 0b12; (which is invalid).
- Null Misuse: Dereferencing a null literal, like String text = null; text.length();, which causes a NullPointerException
Restrictions to Use Underscore (_)
By 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.
Rules
1. No Underscore Before or After a Number:
You can't put underscores before or after an integer.
Example:
int p = _10; or int p = 10_; is invalid.
2. No Underscore Before or After a Decimal Point:
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.
3. No Underscore Before the L or F Suffixes:
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.
4. No Underscore in Places Where a String of Digits is Expected:
Example:
int a = 1__000;
would be invalid due to multiple consecutive underscores.
Valid Use Cases of Underscores
1. Separating Digits in Large Numbers:
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
2. Separating Hexadecimal Digit
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
3. Separating Binary Digits
In binary literals, underscores can also improve readability.
int binaryValue = 0b1101_1010; // Valid binary literal with underscores
4. Floating-Point Literals
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 valuedouble largeDecimal = 123_456_789.987_654_321;
Invalid Use Cases of Underscores
1. Underscore at the Start or End
You cannot use an underscore at the start or end of a numeric literal.
int invalid1 = _1000; // Invalidint invalid2 = 1000_; // Invalid
2. Underscore in the Middle of a Decimal Point
You cannot place an underscore next to the decimal point in floating-point literals.
float invalid = 3.14_15f; // Invalid
3. Underscore in a Hexadecimal or Binary Literal
You cannot use underscores immediately after the 0X, 0B, or 0 prefix.
int invalidHex = 0X_1A; // Invalidint invalidBinary = 0B_1010; // Invalid
4. Multiple Consecutive Underscores
You cannot use multiple consecutive underscores within a numeric literal.
int invalid = 1__000; // Invalid
Example
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
- The program uses underscores in numeric literals (int, double, float, binary, hexadecimal, and octal) to improve readability.
- It assigns values to variables with underscores and prints them to the console.
- The underscores do not affect the numeric values; they are purely for visual clarity.
Conclusion
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.
Learn Industry-Relevant Skills in College for a Strong Tech Career Start!
Explore ProgramFrequently Asked Questions
1. What is a Literal with Example?
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
2. What is a Literal Data Type?
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)
3. What are Identifiers and Literals in Java?
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