Java 7 Underscore in Numeric Literals

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

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.

Are underscores allowed in numeric literals in Java?

It's a feature, new in Java 7. You can rely on it remaining. There are some restrictions, though; see the documentation.

Underscore between digits

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.

You didn't give a good example since 15 is readable even without separating the digits to 1_5. But take for example the number: 100000000000, it's hard to tell what is it without counting digits, so you can do:

100_000_000_000

which makes it easier to identify the number.

In your example, try:

int i = 1_5;
System.out.println(i); //Prints 15

Meaning of 0_0 in Java 7

Underscore characters in numerical literals are allowed in Java 7 just for the readibility purpose. From the javadocs:

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

Underscore in numeric literals

Literals are any thing which you hardcoded in the code like:

int x  = 10;
String str = "hello";

In this 10 and hello are literals.

So numeric literal is nothing but literal having numerical value.

Identifiers are names given to objects, classes etc. but cannot be keywords like int, boolean, null etc.

So in above example x, str and String are identifiers.

SIDE NOTE: How you define numerical literals are different from JDK 6 to JDK 7. So code in question will only run for JDK7

Are underscores allowed in numeric literals in Java?

It's a feature, new in Java 7. You can rely on it remaining. There are some restrictions, though; see the documentation.



Related Topics



Leave a reply



Submit