Java Numeric Literals with Underscore
Last Updated :
24 Nov, 2020
A new feature was introduced by JDK 7 which allows writing numeric literals using the underscore character. Numeric literals are broken to enhance the readability. This feature is used to separate a group of digits in numeric literal which can improve the readability of source code. There are some rules the programmer has to follow before using numeric literals like
1. We should not use underscore before or after an integer number.
int p = _10; // Error, this is an identifier, not a numeric literal
int p = 10_; // Error, cannot put underscores at the end of a number
2. We should not use underscore before or after a decimal point in a floating-point literal.
float a = 10._0f; // Error, cannot put underscores adjacent to a decimal point
float a = 10_.0f; // Error, cannot put underscores adjacent to a decimal point
3. We should not use prior to L or F suffix in long and float integers respectively.
long a = 10_100_00_L; // Error, cannot put underscores prior to an L suffix
float a = 10_100_00_F; // Error, cannot put underscores prior to an F suffix
4. We cannot use underscore in positions where a string of digits is expected.
Example
Java
public class Example {
public static void main(String args[])
{
int a = 7_7;
System.out.println( "The value of a is=" + a);
double p = 11 .239_67_45;
System.out.println( "The value of p is=" + p);
float q = 16 .45_56f;
System.out.println( "The value of q is=" + q);
int c = 0B01_01;
System.out.println( "c = " + c);
int d = 0x2_2;
System.out.println( "d = " + d);
int e = 02_3;
System.out.println( "e = " + e);
}
}
|
Output
The value of a is=77
The value of p is=11.2396745
The value of q is=16.4556
c = 5
d = 34
e = 19
Share your thoughts in the comments
Please Login to comment...