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 yourself that it really makes numbers easier to read.
package org.kodejava.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);
}
}
The results of the code snippet:
maxInt = 2147483647
minInt = -2147483648
maxIntBinary = 2147483647
maxIntHex = 2147483647