Java Literals - Types, Examples and Rules

⏱️ 6 min read • Beginner Level • Lesson 14

Lesson 14 of 124 of Java Tutorial
You have completed this lesson

Completed on . You can revise this lesson or continue to the next topic.

A Java literal is a fixed value written directly in the source code. Literals are used to assign constant values to variables, constants, and expressions.

Before learning literals, it is useful to understand Java variables, Java data types, and Java identifiers.


What are Java Literals?

In Java, a literal is the direct representation of a fixed value in a program. For example, in the statement int age = 20;, the value 20 is an integer literal.

  • A literal is a fixed value written directly in Java source code.

  • Literals are commonly used to assign values to variables and constants.

  • Java supports different types of literals such as integer, floating-point, character, string, boolean, and null literals.

Quick Example

LiteralExample.java
Copy Try Download
public class LiteralExample {

    public static void main(String[] args) {

        int age = 20;
        double salary = 25000.50;
        char grade = 'A';
        String name = "John";
        boolean passed = true;

        System.out.println(age);
        System.out.println(salary);
        System.out.println(grade);
        System.out.println(name);
        System.out.println(passed);
    }
}
  
Explanation:
  • 20 is an integer literal.
  • 25000.50 is a floating-point literal.
  • 'A' is a character literal.
  • "John" is a string literal.
  • true is a boolean literal.

Types of Java Literals

Java provides several types of literals depending on the kind of value represented.

  1. Integer Literals
  2. Floating-Point Literals
  3. Character Literals
  4. String Literals
  5. Boolean Literals
  6. Null Literal

1. Integer Literals

Integer literals represent whole number values. By default, an integer literal is of type int. If it ends with L or l, it becomes a long literal.

Integer Literal Variants

Java integer literals can be written in different number systems such as decimal, binary, octal, and hexadecimal. These variants help represent numeric values in the format that best suits the problem.

IntegerLiteral.java
Copy Try Download
public class IntegerLiteral {
    public static void main(String[] args) {
        int decimal = 100;
        int binary = 0b1100100;
        int octal = 0144;
        int hex = 0x64;

        System.out.println("Decimal value: " + decimal);
        System.out.println("Binary value: " + binary);
        System.out.println("Octal value: " + octal);
        System.out.println("Hexadecimal value: " + hex);
    }
}

Output:

Decimal value: 100
Binary value: 100
Octal value: 100
Hexadecimal value: 100
Explanation: All four literals represent the same value 100, but they are written using different number systems.
  • 100 is a decimal literal.
  • 0b1100100 is a binary literal.
  • 0144 is an octal literal.
  • 0x64 is a hexadecimal literal.

Numeric Literal Separators

Java allows underscores (_) inside numeric literals to improve readability. These underscores do not affect the actual value of the number.

Numeric literal separators were introduced in Java 7. They are commonly used with large numbers, binary values, account numbers, population values, and other long numeric constants. This is also a common Java interview question.

NumericLiteralSeparators.java
Copy Try Download
public class NumericLiteralSeparators {
    public static void main(String[] args) {
        long population = 1_400_000_000L;
        int amount = 10_00_000;
        int binary = 0b1010_1100;
        int hex = 0xCAFE_BABE;

        System.out.println(population);
        System.out.println(amount);
        System.out.println(binary);
        System.out.println(hex);
    }
}

Output:

1400000000
1000000
172
-889275714
Important: Underscores are only for readability. Java ignores them while compiling the program. For example, 1_400_000_000L and 1400000000L represent the same value.

Rules for Using Underscores in Numeric Literals

  • Underscores can be placed between digits.
  • Underscores cannot be placed at the beginning or end of a number.
  • Underscores cannot be placed next to a decimal point.
  • Underscores cannot be placed before suffixes like L, F, or D.
  • Underscores cannot be placed immediately after prefixes like 0x or 0b.
UnderscoreRules.java
Copy Download
int validNumber = 10_00_000;      // Valid
long validLong = 1_400_000_000L;  // Valid
int validBinary = 0b1010_1100;    // Valid

int invalid1 = _1000;     // Invalid: starts with underscore
int invalid2 = 1000_;     // Invalid: ends with underscore
double invalid3 = 12_.5;  // Invalid: before decimal point
double invalid4 = 12._5;  // Invalid: after decimal point
long invalid5 = 1000_L;   // Invalid: before suffix
int invalid6 = 0x_CAFE;   // Invalid: after prefix

Integer literals can be written in decimal, octal, hexadecimal, and binary forms.

Note: Octal literals start with 0, hexadecimal literals start with 0x or 0X, and binary literals start with 0b or 0B.

2. Floating-Point Literals

Floating-point literals represent decimal values with a fractional part. By default, floating-point literals are of type double. To create a float literal, use suffix F or f.

FloatingPointLiterals.java
Copy Try Download
public class FloatingPointLiterals {
    public static void main(String[] args) {
        double price = 223.56;
        float discount = 12.5F;
        double scientific = 1.25e3;

        System.out.println(price);
        System.out.println(discount);
        System.out.println(scientific);
    }
}

Output:

223.56
12.5
1250.0

3. Character Literals

A character literal represents a single character enclosed in single quotes. Java also supports Unicode escape sequences for characters.

CharacterLiterals.java
Copy Try Download
public class CharacterLiterals {
    public static void main(String[] args) {
        char letter = 'A';
        char symbol = '@';
        char unicodeChar = '\u0041';

        System.out.println(letter);
        System.out.println(symbol);
        System.out.println(unicodeChar);
    }
}

Output:

A
@
A

Escape Sequences in Character Literals

In Java, escape sequences are special character combinations that start with a backslash (\). They are used to represent characters that are difficult to type directly, such as a new line, tab space, backslash, single quote, or double quote.

Escape Sequence Meaning Example Usage
\n New Line System.out.println("Hello\nJava");
\t Tab System.out.println("Hello\tJava");
\\ Backslash System.out.println("C:\\Java");
\' Single Quote char quote = '\'';
\" Double Quote System.out.println("He said \"Hello\"");
EscapeSequencesExample.java
Copy Try Download
public class EscapeSequencesExample {
    public static void main(String[] args) {
        System.out.println("Hello\nJava");
        System.out.println("Hello\tJava");
        System.out.println("C:\\Java");

        char singleQuote = '\'';
        System.out.println(singleQuote);

        System.out.println("He said \"Hello\"");
    }
}

Output:

Hello
Java
Hello   Java
C:\Java
'
He said "Hello"
Remember: Escape sequences are useful when you want to print special characters or format output. For example, \n moves text to a new line, and \t adds tab spacing.

4. String Literals

A string literal is a sequence of characters enclosed in double quotes. In Java, string literals create objects of the String class.

StringLiterals.java
Copy Try Download
public class StringLiterals {
    public static void main(String[] args) {
        String message = "Java Prowess";
        String greeting = "Welcome to ProwessApps";

        System.out.println(message);
        System.out.println(greeting);
    }
}

Output:

Java Prowess
Welcome to ProwessApps

5. Boolean Literals

Boolean literals represent truth values. Java has only two boolean literals: true and false.

BooleanLiterals.java
Copy Try Download
public class BooleanLiterals {
    public static void main(String[] args) {
        boolean isJavaEasy = true;
        boolean isKeywordIdentifier = false;

        System.out.println(isJavaEasy);
        System.out.println(isKeywordIdentifier);
    }
}

Output:

true
false
Important: Java does not allow 0 or 1 as boolean values. Only true and false are valid boolean literals.

6. Null Literal

The null literal represents the absence of an object reference. It can be assigned to reference variables such as objects, arrays, and strings, but not to primitive variables.

NullLiteral.java
Copy Try Download
public class NullLiteral {
    public static void main(String[] args) {
        String name = null;

        System.out.println(name);
    }
}

Output:

null

Java Literals Summary Table

Literal Type Example Meaning
Integer Literal 100, 0x13A, 0b101 Whole number value
Floating-Point Literal 10.5, 12.5F Decimal number value
Character Literal 'A', '@' Single character
String Literal "Java" Sequence of characters
Boolean Literal true, false Logical truth value
Null Literal null No object reference

Common Mistakes

  • Using double quotes for char literals.
  • Using single quotes for String literals.
  • Assigning null to primitive variables.
  • Confusing character literals with String literals.
Summary:
  • A literal is a fixed value written directly in Java source code.
  • Java supports integer, floating-point, character, string, boolean, and null literals.
  • Integer literals can be written in decimal, octal, hexadecimal, and binary forms.
  • Numeric literal separators use underscores to improve readability and were introduced in Java 7.
  • Floating-point literals are double by default unless suffixed with F or f.
  • Boolean literals can only be true or false.
  • Escape sequences are used to represent special characters such as new line, tab, quotes, and backslash.

Interview Questions ⭐

Literals in Java are fixed values written directly in the source code, such as numbers, characters, strings, true, false, and null.

Java has several types of literals including integer literals, floating-point literals, character literals, string literals, boolean literals, and null literal.

An integer literal represents a whole number value. It can be written in decimal, octal, hexadecimal, or binary form.

The default type of a floating-point literal in Java is double. To create a float literal, use the suffix F or f.

No, Java boolean literals can only be true or false. Values like 0 and 1 are not allowed as boolean literals.

A string literal is a sequence of characters enclosed in double quotes. In Java, string literals are objects of the String class.

The null literal represents the absence of an object reference and can be assigned to reference variables, but not to primitive variables.

Next step: Learn Java Escape Sequences

🚀 Continue to Java Escape Sequences →

🧠 Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: Literals | Language: Java

Question 1 of 5
Q1. What are the only possible values for a boolean literal in Java?
Q2. Which of the following correctly defines a string literal in Java?
Q3. Which of the following represents a valid character literal in Java?
Q4. Which of the following is NOT a valid integer literal in Java?
Q5. What is the default type of a floating-point literal in Java?

🎉 Great job! Continue learning Java step by step.

Discussion

Ask questions, share suggestions, or discuss this lesson.

Please login or create an account to join the discussion and save your learning activity.

Loading comments...

Have you completed this lesson?

Mark this lesson as completed to track your learning progress. To keep track across devices, please login and save your learning progress.

Not completed yet.