Search code examples
javajava-7

How do Numeric literals with underscore work in Java and why was it added as part of jdk 1.7?


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;

Solution

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