Can somebody please explain to me why this feature was added in JDK 7 and how it works?
While going through the new features of JDK 7, I found following code.
int i;
//Java 7 allows underscore in integer
i=3455_11_11;
In Java SE 7 and later, any number of underscore characters ( _ ) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
An exact numeric literal is a numeric value without a decimal point, such as 65,– 233, and +12. Using the Java integer syntax, exact numeric literals support numbers in the range of a Java long. An approximate numeric literal is a numeric value in scientific notation, such as 57.,– 85.7, and +2.1.
When Java was introduced, use of underscore in numeric literals was not allowed but from java version 1.7 onwards we can use '_' underscore symbols between digits of numeric literals. You can place underscores only between digits.
You cannot use underscore in positions where a string of digits is expected.
This is used to group the digits in your numeric (say for example for credit card etc)
From Oracle Website:
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
To conclude, it's just for a sake of readability.
See Underscores in Numeric Literals:
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
Try this:
int num = 111_222;
System.out.println(num); //Prints 111222
This feature was added due to the fact that long numbers can be hard to read sometimes, so instead of counting how many "zeros" a number has to figure out if it's a million or one hundred thousand, you can do:
int myNum = 1_000_000;
Now it's easy to see that there is two groups of 3 zeros, and clearly the number is million. Compare it with:
int myNum = 1000000;
Admit.. here you had to count each zero..
JDK 7 _
for numeric literals feature is only for the sake of readability. As per docs:
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With