Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore between digits [duplicate]

Tags:

java

int

java-7

Mistakenly an underscore has been added like below:

int i = 1_5;

But no compilation error. Why is so? Output is coming as if underscore is ignored. Then why such feature in Java?

like image 788
Leo Avatar asked Jan 06 '15 13:01

Leo


People also ask

What does underscore mean in numbers?

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.

In which of the following options the usage of underscore character () is incorrect?

You cannot use underscore in positions where a string of digits is expected.

What is the maximum number of underscore character?

Explanation: Theoretically, there is no limit on the number of underscores. 17) Java uses UTF-16 Unicode format to represent characters.


2 Answers

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
like image 75
Maroun Avatar answered Nov 15 '22 16:11

Maroun


That is the new feature, valid since Java 7. It improves readability of your literal values.

According to Mala Gupta's OCA_Java_SE_7_Programmer_I_Certification_Guide_Exam_1Z0-803:

Pay attention to the use of underscores in the numeric literal values. Here are some of the rules:

1) You can’t start or end a literal value with an underscore.

2) You can’t place an underscore right after the prefixes 0b, 0B, 0x, and 0X, which are used to define binary and hexadecimal literal values.

3) You can place an underscore right after the prefix 0, which is used to define an octal literal value.

4) You can’t place an underscore prior to an L suffix (the L suffix is used to mark a literal value as long).

5) You can’t use an underscore in positions where a string of digits is expected.

Valid examples:

long baseDecimal = 100_267_760;
long octVal = 04_13;
long hexVal = 0x10_BA_75;
long binVal = 0b1_0000_10_11;

Invalid examples:

int intLiteral = _100;
int intLiteral2 = 100_999_;
long longLiteral = 100_L;
like image 37
Filip Avatar answered Nov 15 '22 16:11

Filip