Do you know Java: Underscores in Numeric Literals


Underscore can be used in numeric literals to group digits in a numeric value. This way that can enhance code readability, decrease mistyping and helps visually keeping numeric values in range.

Code readability is one of the most important viewpoints of software development. The more readable the code is, the faster that can be understood by developers.
Java 7 introduced underscore as a comfortable way to separate digits of a numeric value into groups.

int ____j = 0x5_4;
byte b = 1_2_7;
short s = 32_767;
int i = 1_000_000;
long l = 1_000_000_000_000L;
float f = 1_000.5f;
double d = 1_000.5d;

Naming a few limitations:

  • If value is prefixed with underscore(s) then that is identifier: int j = _10;
  • Underscore is not allowed to be at the end: int j = 10_;
  • Code does not compile if underscore is before or after x in hex values: int j = 0_x_10;
  • Code also does not compile if underscore is after leading zero of octal values: int j = 0_10;
  • Underscore is not allowed to be before or after dot in float or double values: double d = 1._234d;
  • If underscore is immediately before the type suffix like f, d or L: double d = 1.234_d;

Underscore helps separating digits into groups, thus make long values more readable.

Code can be found: https://github.com/torokmark/do-you-know-java