Java Numeric Literals with Underscore

Java allows the use of underscores in numeric literals to improve readability. An underscore can be placed between any two digits in a numeric literal, with the exception of the first and last digits. Here are some examples:

int a = 1_000_000;
long b = 123_456_789L;
double c = 3.14_15_92_65;
float d = 1.234_567f;

In the above examples, the underscores are used to separate groups of digits for easier reading. The values of a, b, c, and d are all the same as they would be without the underscores. The L at the end of b is required because 123_456_789 is a long literal.

Underscores cannot be placed at the beginning or end of a numeric literal, or adjacent to a decimal point or exponent indicator. For example, the following are not valid:

int e = _1_000_000;      // invalid: cannot start with an underscore
long f = 123_456_789_;   // invalid: cannot end with an underscore
double g = 3._14_15_92;   // invalid: cannot be adjacent to decimal point
float h = 1.234_567_f;    // invalid: cannot be adjacent to suffix
int i = 1.2_e3;           // invalid: cannot be adjacent to exponent indicator

Using underscores in numeric literals is purely for readability purposes and has no effect on the value of the literal.

Underscores in Numeric Literals Example:

Sure, here’s an example that demonstrates the use of underscores in numeric literals:

public class NumericLiteralsExample {
    public static void main(String[] args) {
        int a = 1_000_000;
        long b = 123_456_789L;
        double c = 3.14_15_92_65;
        float d = 1.234_567f;

        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        System.out.println("d = " + d);
    }
}

When you run this program, it will output the following:

a = 1000000
b = 123456789
c = 3.14159265
d = 1.234567

As you can see, the underscores are ignored by the compiler, and the output is the same as if they were not there. However, the use of underscores can make the code more readable, especially when dealing with large numbers.