How to use underscore in numeric literals?

Writing a long sequence of numbers in a code is a hard stuff to read. In the new feature introduced by JDK 7 we are now allowed to write numeric literals using the underscore character to break the numbers to make it easier to read.

You can see how to use underscore in numeric literals in the following examples. And you’ll see it for your self that it really makes numbers easier to read.

package org.kodejava.example.basic;

public class UnderscoreNumericExample {
    public static void main(String[] args) {
        // Write numeric literals using underscore as an easier way
        // to read long numbers.
        int maxInt = 2_147_483_647;
        int minInt = -2_147_483_648;

        if (maxInt == Integer.MAX_VALUE) {
            System.out.println("maxInt = " + maxInt);

        if (minInt == Integer.MIN_VALUE) {
            System.out.println("minInt = " + minInt);

        // Write numbers in binary or hex literals using the
        // underscores.
        int maxIntBinary = 0B111_1111_1111_1111_1111_1111_1111_1111;
        int maxIntHex    =   0X7____F____F____F____F____F____F____F;

        System.out.println("maxIntBinary = " + maxIntBinary);
        System.out.println("maxIntHex    = " + maxIntHex);


Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.