Skip to content
Related Articles

Related Articles

Java Numeric Literals with Underscore
  • Last Updated : 24 Nov, 2020
GeeksforGeeks - Summer Carnival Banner

 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




// Java program to demonstrate Numeric Literals with
// Underscore
  
public class Example {
    public static void main(String args[])
    {
        // Underscore in integral literal
        int a = 7_7;
        System.out.println("The value of a is=" + a);
  
        // Underscore in floating literal
        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);
  
        // Underscore in binary literal
        int c = 0B01_01;
        System.out.println("c = " + c);
  
        // Underscore in hexadecimal literal
        int d = 0x2_2;
        System.out.println("d = " + d);
  
        // Underscore in octal literal
        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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :