Java Numeric Literals

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Numeric Literals with Underscore

Java allows you to use underscore in numeric literals. This feature was introduced in Java 7. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your source code.

The following points are considerable:

  • You cannot use underscore at the beginning or end of a number.
  1. Ex. int a = _10; // Error, this is an identifier, not a numeric literal  

  2. Ex. int a = 10_; // Error, cannot put underscores at the end of a number  

  • You cannot use underscore adjacent to a decimal point in a floating point literal.
  1. Ex. float a = 10._0; // Error, cannot put underscores adjacent to a decimal point  

  2. Ex. float a = 10_.0; // Error, cannot put underscores adjacent to a decimal point  

  • You cannot use underscore prior to an F or L suffix
  1. Ex. long a = 10_100_00_L; // Error, cannot put underscores prior to an L suffix  

  2. Ex. float a = 10_100_00_F; // Error, cannot put underscores prior to an F suffix  

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


Underscores in Numeric Literals Example

  1. public class UnderscoreInNumericLiteralExample {  
  2.     public static void main(String[] args) {  
  3.         // Underscore in integral literal  
  4.         int a = 10_00000;  
  5.         System.out.println("a = "+a);  
  6.         // Underscore in floating literal  
  7.         float b = 10.5_000f;  
  8.         System.out.println("b = "+b);  
  9.         // Underscore in binary literal  
  10.         int c = 0B10_10;  
  11.         System.out.println("c = "+c);  
  12.         // Underscore in hexadecimal literal  
  13.         int d = 0x1_1;  
  14.         System.out.println("d = "+d);  
  15.         // Underscore in octal literal  
  16.         int e = 01_1;  
  17.         System.out.println("e = "+e);  
  18.     }  
  19. }  

Output:

a = 1000000
b = 10.5
c = 10
d = 17
e = 9