Literals in Java

Naveen AnamaneniUpdated · 5 min read

In int fare = 450;, the variable is fare, but 450 is something else: a value written directly into the code. That fixed value is a literal. Java has a literal for every basic type, and a few small details, such as an L on the end of a big number or an f on a decimal, decide whether your code compiles.

Every Kind of Literal

Every kind of literal, with examples
KindExamplesType
Integer42, -7, 1_00_000int
Integer with L9_000_000_000Llong
Floating point3.14, 1.5e3double
Floating point with f2.5ffloat
Character'A', '\n', '₹'char
String"Pune", ""String
Text block""" ... """String
Booleantrue, falseboolean
Nullnullany reference type

Whole Numbers in Four Bases

The same number can be written four ways:

Bases.java▶ Try it
public class Bases {
    public static void main(String[] args) {
        int decimal = 42;
        int hex = 0x2A;
        int binary = 0b101010;
        int octal = 052;
        System.out.println(decimal + " " + hex + " " + binary + " " + octal);
 
        int lakh = 1_00_000;
        long distanceToMoonMm = 384_400_000_000L;
        System.out.println(lakh + " and " + distanceToMoonMm);
    }
}
Output
42 42 42 42
100000 and 384400000000

How it works

  1. Lines 3 to 6 all store 42: decimal (normal), hexadecimal with 0x, binary with 0b, and octal with a leading 0.
  2. Line 9 uses underscores to group digits. Java ignores them, so you can write a lakh the Indian way: 1_00_000.
  3. Line 10 ends with L because the number is too big for an int. Without it, the compiler stops with integer number too large.
  4. Underscores are only for people reading the code; the printed numbers have none.

Try it yourself: remove the leading zero from 052 on line 6 and run it again. Why does the last number on the first line change?

Decimals: double by Default

A literal with a decimal point is a double. To store it in a float, add f:

Compiler output
FloatLit.java:3: error: incompatible types: possible lossy conversion from double to float
        float f = 2.5;
                  ^

float f = 2.5f; compiles. Scientific notation works too: 1.5e3 means 1.5 × 10³, which is 1500.0.

Characters, Strings and Text Blocks

  • A char literal is one character in single quotes: 'A'. Escape sequences start with a backslash: '\n' (new line), '\t' (tab), '\'' (single quote), '\\' (backslash).
  • A String literal is text in double quotes: "Platform 5".
  • A text block (Java 15+) is multi-line text between """ and """. Line breaks are kept and you don't need \n:
Receipt.java▶ Try it
public class Receipt {
    public static void main(String[] args) {
        String receipt = """
                Fresh Mart
                Rice 5 kg   Rs. 340
                Total       Rs. 340
                """;
        System.out.print(receipt);
    }
}
Output
Fresh Mart
Rice 5 kg   Rs. 340
Total       Rs. 340

Java removes the common indentation, so the text block can be indented to match your code. A text block starts on the line after the opening """.

true, false and null

true and false are the two boolean literals. null means "no object" and can be stored in any reference variable, such as a String, but never in a primitive like int.

Common Mistakes

Forgetting L on big numbers. long big = 9000000000; fails with integer number too large, because the literal itself is an int until you add L.

Writing float f = 2.5;. The literal is a double; add f.

Padding numbers with zeros. 012 is octal 10, not twelve.

Putting underscores in the wrong place. _100, 100_ and 1._5 don't compile. Underscores must sit between digits.

Practice

  1. Easy: Write ten crore (100,000,000) with underscores in the Indian style, and print it.
  2. Harder: Print a three-line train ticket using a text block, with the train name, the coach and seat, and the fare.

Quick check: Literals

4 questions
1Which literal is a long?
2What value does 0x1F have?
3Why doesn't float price = 99.5; compile?
4What does int code = 010; store?

Key Takeaways

Was this tutorial helpful?

Lesson 37 of 482