Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are the underscores in numeric literals in Java?


Underscores (_) in numeric literals are one of Java 7’s features. Any numeric literal, such as int, byte, short, float, long, or double, can have underscores between its digits. When you use underscores in numeric literals, you may separate them into groups for better readability.

Points to keep in mind before using underscores

  • Underscores can only be between digits and numerals.

  • There are no underscores allowed adjacent to decimal places, the L/F suffix, or the radix prefix. As a result, 10_.32, 8_L, and 0x _343 are incorrect and will result in a compilation error.

  • Between numbers, multiple underscores are permitted. Therefore, 10___1239 is an acceptable number.

  • At the end of a literal, you can’t use underscores. As a result, 543_ is invalid, resulting in a build time error.

  • When an underscore is placed before a number literal, it is interpreted as an identifier rather than a numeric literal. For example: int _10=0;, int x = _10;.

  • When expecting a string with numbers, underscores can’t be used. For example, Integer.parseInt("10__90"), throws java.lang. NumberFormatException.

public class Main{

    public static void main(String[] args) {
        // single underscore between digits
        long ssn = 132_43_6543L;

        // multiple underscores between digits
        long ssnMultipleUnderscores = 132_43_654____3L;

        // underscore in floating point
        float floatingPoint = 10.32_5F;

        // underscores between bytes
        long hexadecimalBytes = 0xFF_EC_DE_5E;

        // underscores between words
        long hexadecimalWords = 0xCAFE_BABE;

        // underscores in binary
        byte byteInBinary = 0b0010_0101;

        // underscores in addition
        int add = 12_3 + 4_5_6;

Invalid underscores

The following syntax with underscores is invalid and will lead to compilation errors.

long ssnInvalid = 132_43_6543L_;
long ssnInvalid = _132_43_6543L;
float floatingPointInvalid = 10._32_5F;
float floatingPointInvalid = 10_.32_5F;



View all Courses

Keep Exploring