Java has allowed using of underscore in numeric literals from Version 7. Underscores are ignored at runtime and help code easy to read. They can be used in both whole and floating point numbers. There are some restrictions to use. It can not be placed before the first number or after the last number. It can not be used adjacent to decimal point. It also can not be places before f or l suffix (float and long suffix).

Example:

long myLong = 110_111_21_112l;

int myInt = 110_111_21;

float myFloat = 110_11.1_21_112f;

double myDouble = 110_11.1_21_112d;

 

If you print above 4 statements in console, here is the output:

int: 11011121
long : 11011121112
float : 11011.121
double : 11011.121112

 

Advertisements