Wednesday, July 3, 2024
HomeLanguagesJavaUsing underscore in Numeric Literals in Java

Using underscore in Numeric Literals in Java

A new feature was introduced by JDK 7 which allows writing numeric literals using the underscore character. Basically, they are broken to enhance readability. This feature enables us to separate groups of digits in numeric literals, which improves the readability of code. For instance, if our code contains numbers with many digits, we can use an underscore character to separate digits in groups of three, similar to how we would use a punctuation mark like a comma, or a space, as a separator. Let us explore further with an example

Example

Java




// Java Program to Illustrate Different Ways of Usage
// of Underscore in Numeric Literals
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Declaring and initializing values of
        // integer, long, float and double datatype
 
        // Integer literal
        int inum = 1_00_00_000;
        // Long literal
        long lnum = 1_00_00_000;
        // Float literal
        float fnum = 2.10_001F;
        // Double literal
        double dnum = 2.10_12_001;
 
        // Printing and displaying values on console
        System.out.println("inum:" + inum);
        System.out.println("lnum:" + lnum);
        System.out.println("fnum:" + fnum);
        System.out.println("dnum:" + dnum);
    }
}


Output

inum:10000000
lnum:10000000
fnum:2.10001
dnum:2.1012001

This article is contributed by Twinkle Tyagi. If you like Lazyroar and would like to contribute, you can also write an article and mail your article to review-team@neveropen.co.za. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments