How Numeric literal with underscore works in java and why it was added as part of jdk 1.7

JavaJava 7

Java Problem Overview


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;

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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..

Solution 3 - Java

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.

Solution 4 - Java

The underscore is completely ignored in Integer literals. It may be added to, for example, group digits in long numbers in groups of 3 (like you do in texts).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDark KnightView Question on Stackoverflow
Solution 1 - JavaPradeep SimhaView Answer on Stackoverflow
Solution 2 - JavaMarounView Answer on Stackoverflow
Solution 3 - JavaJuned AhsanView Answer on Stackoverflow
Solution 4 - JavaJohannes H.View Answer on Stackoverflow