16

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?

gnat
  • 6,213
  • 108
  • 53
  • 73
Leo
  • 5,017
  • 6
  • 32
  • 55

2 Answers2

27

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
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • If only there was some way we could put comments next to code :/ – musefan Jan 06 '15 at 13:20
  • 5
    We must not provide comments in order to clarify the language semantics, instead we must learn the language (or use google / stackoverflow). – Gio Jan 06 '15 at 13:23
5

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;
Filip
  • 2,244
  • 2
  • 21
  • 34