• Articles
  • Tutorials
  • Interview Questions

Literals in Java: Types of Literals

Through this blog article, we go on a fascinating journey to discover the many sorts of literals in Java and their hidden potential. Join us as we explore this enthralling adventure and learn the magic of Java literals.

Table of Contents

To improve your Java skills and start coding like a pro, watch our YouTube video!

What are Literals in Java?

In Java, literals are fixed values that are directly written in the source code. They represent constant values that do not change during program execution. Let me provide you with a concise example to illustrate the concept of Java literals.

Consider a simple program where we want to calculate the area of a circle. We can declare a variable to store the radius and assign it a literal value using the below-mentioned code:

public class CircleArea {
    public static void main(String[] args) {
        double radius = 5.0; // Literal value representing the radius
        double area = Math.PI * radius * radius; // Calculating the area
        System.out.println("The area of the circle is: " + area);
    }
}

In this example, the literal value 5.0 represents the circle radius. It is directly assigned to the radius variable. The program then uses this value to calculate the circle area using the mathematical formula Math.PI * radius * radius. Finally, the calculated area value is printed on the console.

Here, the literal value 5.0 remains constant throughout the program execution as it represents a fixed radius. It demonstrates the usage of a numeric literal in Java.

Are you ready to advance your Java knowledge? Enroll in our thorough Java course today to maximize your potential!

Types of Literals in Java

In Java, there are several types of literals, each representing a specific type of constant value. Let’s explore each type in detail and provide an example for better understanding.

Types of Literals in Java

Numeric Literals

Numeric literals represent numerical values and can be expressed in different formats. The common formats are mentioned below:

  1. Decimal: It represents values in the base-10 system using digits 0–9. 
    Example: 12345
  1. Octal: It represents values in the base-8 system using digits 0–7 and prefixes the value with 0.
    Example: 0123
  1. Hexadecimal: It represents values in the base-16 system using digits 0–9 and letters A–F, prefixing the value with 0x or 0X. 
    Example: 0xABCD
  1. Binary: It represents values in the base-2 system using digits 0 and 1, prefixing the value with 0b or 0B. 
    Example: 0b1010
int decimal = 42;        // Decimal literal
int octal = 012;         // Octal literal (decimal 10)
int hexadecimal = 0x1A;  // Hexadecimal literal (decimal 26)
int binary = 0b1010;     // Binary literal (decimal 10)

Get 100% Hike!

Master Most in Demand Skills Now !

Character Literals

Character literals denote single characters enclosed in single quotes (”). They can represent Unicode characters as well, using an escape sequence. Here are some important points about character literals:

Character Literals

1.  Basic Characters

Character literals can be utilized to represent basic characters like letters, digits, and symbols. For example:

char letterA = 'A';        // Character literal for the letter 'A'
char digit7 = '7';         // Character literal for the digit 7
char dollarSign = '$';     // Character literal for the dollar sign
char plusSign = '+';       // Character literal for the plus sign

2. Escape Sequences

Character literals also support escape sequences, which represent special characters using a backslash (”) followed by a specific character. Some commonly used escape sequences are mentioned below:

  • '\n': Newline character
  • '\t': Tab character
  • '\\': Backslash character
  • '\': Single quote character
  • '\uXXXX': Unicode character, represented by its hexadecimal value

Example:

char newline = '\n';       // Character literal for a newline
char tab = '\t';           // Character literal for a tab
char carriageReturn = '\r'; // Character literal for a carriage return
char singleQuote = '\'';   // Character literal for a single quote
char backslash = '\\';     // Character literal for a backslash

3. Unicode Characters

Character literals are also utilized to denote Unicode characters using the escape sequence ‘\uXXXX,’ where ‘XXXX’ is the hexadecimal representation of the Unicode value. This allows you to work with characters from different languages and symbol sets.

Example:

char omega = '\u03A9';     // Character literal for the Greek letter Omega (Ω)
char alpha = '\u03B1';     // Character literal for the Greek letter Alpha (α)
char heart = '\u2665';     // Character literal for the heart symbol (♥)

Want to ace your next Java interview? Check out our recent blog post about the most common Java interview questions and answers!

String Literals

String literals represent sequences of characters enclosed in double quotes (“x”). They can contain any combination of letters, numbers, symbols, and escape sequences. Escape sequences in strings are similar to character literals.

Example:

String greeting = "Hello, world!";              // String literal
String path = "C:\\Program Files\\Java\\";      // String literal with backslashes
String unicodeString = "\u03A9\u03B1\u03B2\u03B3";  // String literal with Unicode characters (Ωαβγ)

Boolean Literals

Boolean literals represent Boolean values; they can have only two possible values: ‘true’ or ‘false’.

boolean isActive = true;    // Boolean literal representing an active state
boolean isFinished = false; // Boolean literal representing a finished state

Null Literal

Null Literal

The null literal represents the absence of a value. It is often used to indicate that a reference type variable does not refer to any object. Here are some important points about the null literal:

1. Reference Types

In Java, objects are created from classes, and variables of reference types hold references to these objects. When a reference type variable is assigned the null literal, it means that it does not currently point to any valid object in memory.

2. Default Value

If you declare a reference type variable without initializing it, its default value is set to null. For example:

String name;  // Declared but not initialized, default value is null

3. Assigning Null

You can explicitly assign the null literal to a reference type variable using the assignment operator (=). This is often done when you want to indicate that the variable has no valid object reference. For instance:

String name = null;  // Assigning the null literal to the variable

4. Null Safety

When working with null reference variables, it’s important to handle them carefully to avoid NullPointerExceptions. If you try to access a member or invoke a method on a null reference, it will result in a NullPointerException at runtime. Hence, it is crucial to check if a variable is null before performing any operations on it. The below-mentioned code is a sample to show you the same:

String name = null;
if (name != null) {
    // Perform operations on the name variable
    System.out.println(name.length());  // Avoiding NullPointerException
} else {
    System.out.println("Name is null");
}

5. Comparison

The null literal can be used for comparison to determine if a reference variable is null or not. This is often done using the equality operator (==) or the inequality operator (!=). Refer to the below-mentioned code for an example of the same:

String name = null;
if (name == null) {
    System.out.println("Name is null");
} else {
    // Perform operations on the name variable
    System.out.println(name.length());
}

Get a Complete Hands-on on Java through our Java Tutorial.

Conclusion

In the end, literals in Java play an important role in programming by offering a simple mechanism to express fixed values within the code. They act as constants that improve readability and maintainability, allowing developers to comprehend and adjust the code more easily. 

Integers, floating-point numbers, characters, booleans, and strings are among the data types for which Java literals are accessible. They may be used in expressions, method parameters, and even as arguments in built-in Java methods; thus, their application goes beyond basic value assignments.

Join our Intellipaat community today and interact with other developers all over the world! Join now and push your Java abilities to new heights!

Course Schedule

Name Date Details
Python Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 11 May 2024(Sat-Sun) Weekend Batch
View Details

Full-Stack-ad.jpg