Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wierd Syntax - Underscores between digits [duplicate]

Tags:

java

syntax

Per my usual, I have been working on more UIL Java practice sheets when I came across this problem:

int _ = 8;
System.out.println(5_5);

The question was "What is the output of the following code piece?"

My first guess was a syntax error, but the correct response is actually 55.

Why is this?

like image 585
Will Sherwood Avatar asked Aug 11 '13 19:08

Will Sherwood


1 Answers

From Java 7, you can have underscores in between digits, to improve readability:

From JLS - Section 3.10.1 and JLS Section 3.10.2:

Underscores are allowed as separators between digits that denote the integer.

For floating point literal also:

Underscores are allowed as separators between digits that denote the whole-number part, and between digits that denote the fraction part, and between digits that denote the exponent.

For e.g., 1000000000 can now be written as 1_000_000_000. So, it is better for eyes, isn't it.

Similarly you can write - 0x7fff_ffff, 0b0111_1111.

And regarding variable name, _ is a valid variable name. As per Java standard, a variable name should start with a $, _ or a letter.

like image 149
Rohit Jain Avatar answered Sep 22 '22 00:09

Rohit Jain