Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are underscores allowed in numeric literals in Java?

Can you use underscores in numbers in Java? I saw this code in a blog, and it works, but will it continue to work in the future? Is it a feature or a bug?

long oneBillion = 1_000_000_000L;
like image 619
stevemcl Avatar asked May 19 '14 19:05

stevemcl


People also ask

Can we use underscore in int in Java?

Underscores ( _ ) in numeric literals are one of Java 7's features. Any numeric literal, such as int , byte , short , float , long , or double , can have underscores between its digits.

Which of the following is not a valid numeric literal in Java?

In most of programming language like Java and C/C++ , the number with leading zero are interpreted as octal number. As we know octal numbers are only represented within 0 to 7 digits only. Hence numbers like 05 , 03 , 054 are valid but the numbers like 078 , 0348 , 09 , 08 are tends to invalid.

What are the valid numeric literal in Java?

The following rules govern the formation of numeric literals: A literal must contain at least one digit. A literal must contain no more than one sign character and, if one is used, it must be the leftmost character of the string. A literal must not contain more than one decimal point.

In which of the following usage of underscore is incorrect?

You cannot use underscore at the beginning or end of a number. You cannot use underscore adjacent to a decimal point in a floating point literal. You cannot use underscore in positions where a string of digits is expected.


2 Answers

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

like image 94
asthasr Avatar answered Oct 20 '22 14:10

asthasr


Java 7 supports the feature of having underscores in the numeric literals to improve the readability of the values being assigned.

but the underscore usage is restricted to be in between two numeric digits, i.e not at the beginning or ending of the numeric values but should be confined between two digits, should not be as a prefix to l,f used to represent long and float values and not in between radix prefixes also.

like image 29
Vamshi Krishna Alladi Avatar answered Oct 20 '22 13:10

Vamshi Krishna Alladi