Basics

14. Numeric Literals and Underscores

Java supports binary (0b), octal (0), and hex (0x) integer literals, plus underscore separators in numeric literals for readability โ€” underscores may not appear at the start, end, or next to a radix prefix.

Java 7+ (underscores); Java 21 (core language)

Explanation

Since Java 7, you can insert underscores anywhere in a numeric literal except at the start, end, adjacent to a decimal point, or adjacent to a radix prefix (0x, 0b). Underscores are purely visual โ€” the compiler ignores them.

Radix prefixes: 0x or 0X for hexadecimal, 0b or 0B for binary (Java 7+), and a leading 0 for octal (be careful โ€” 017 is 15 decimal, not 17!). The L or l suffix marks a long literal; F or f marks float; no suffix on a floating-point literal means double. Prefer L over l (lowercase L looks like 1).

Example

public class NumericLiterals {
    public static void main(String[] args) {
        // Underscore separators (Java 7+)
        int million      = 1_000_000;
        long creditCard  = 1234_5678_9012_3456L;
        int hexColor     = 0xFF_EC_2A_1C;
        int binaryMask   = 0b1111_0000_1111_0000;

        System.out.println("Million:     " + million);       // 1000000
        System.out.println("Hex color:   " + Integer.toHexString(hexColor)); // ffec2a1c
        System.out.println("Binary mask: " + Integer.toBinaryString(binaryMask));

        // Radix literals
        int decimal = 255;
        int hex     = 0xFF;        // 255
        int binary  = 0b1111_1111; // 255
        int octal   = 0377;        // 255 (careful: leading 0 = octal!)
        System.out.println(decimal == hex && hex == binary && binary == octal); // true

        // Octal trap
        int notSeventeen = 017;  // This is 15, not 17!
        System.out.println("017 decimal = " + notSeventeen); // 15

        // Long and float suffixes
        long bigNum   = 9_999_999_999L;  // L suffix required for > Integer.MAX_VALUE
        float pi      = 3.14F;           // F suffix
        double precise = 3.14159_26535;  // double (default for floating-point)

        System.out.println("Long: " + bigNum);
        System.out.printf("Float: %.2f, Double: %.5f%n", pi, precise);
    }
}

Sources