**Underscores in Numeric literals** are allowed starting from Java 7, to improve the readability of large numbers.

## Underscores in Numeric Literals Java 7

Suppose if you want to represent a large number like 1 trillion in java code, you will represent it as 1000000000000. Until you name the variable name as 1 trillion, developers can’t understand the value just by looking at the number.

How about representing it as 1,000,000,000,000? Yes, this is more readable and based on the number of commas (,), you can easily figure out the value.

## Underscores in Numeric Literals

Underscores in Numeric literals is exactly the same concept explained above. But we are not going to separate large numbers by comma (,), but with underscore(_). Since comma already has a significance in Java like for separation of variables, they might have come-up with underscore.

So from Java 7, you can start representing numbers using underscores.

**Examples:**

Below are some of *valid* and *invalid* scenarios to use underscore(_):

- It should be used only between digits like
- Valid
long aadharCardNumber = 9632_5874_1236_5478L;

- Valid
- It cannot be used at the beginning of the number
- Valid
long hexBytes =0xFF_EC_DE_5E;

- Invalid
long hexBytes = _0xFF_EC_DE_5E;

- Valid
- It cannot be used at the end of number
- Valid
float dollarValue = 66.77_5f;

- Invalid
float dollarValue = 66.77_5_f;

- Valid
- It cannot be used next to a decimal point in floating point number
- Valid
double petrolPrice = 77.24;

- Invalid
double petrolPrice = 77._24l

- Valid
- It cannot be used before F(floating) and L(long) suffixes
- Valid
private static final long serialVersionUID = 4046799913406610513L;

- Invalid
private static final long serialVersionUID = 4046799913406610513_L;

- Valid
- In positions where a String of digits expected like parsing in wrapper classes
- Valid
Float pi = Float.parseFloat("3.14");

- Invalid
Float pi = Float.parseFloat("3.1_4"); //throws NumberFormatException

- Valid

**Points to note:**

We can use underscores (_) only in between the digits; you cannot place underscores in the following places:

- We can not use beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an F or L suffix
- In positions where a string of digits is expected

Happy Learning 🙂

## Leave A Comment