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.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);
}
}
The results of the code snippet:
maxInt = 2147483647
minInt = -2147483648
maxIntBinary = 2147483647
maxIntHex = 2147483647
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019