Underscores in Numeric Literals - Java 7 Feature With Examples

One of the Java 7 features is underscores in numeric literals. You can place underscores between digits of any numeric literal like int, byte, short, float, long, double. Using underscores in numeric literals will allow you to divide them into groups for better readability.

Underscores in Numeric Literals

Let’s see underscores in numeric literals in action:

The above program compiles fine and here is the output:

Tips for Underscores in Numeric Literals

  • Underscores can be placed only between digits.
  • You can’t put underscores next to decimal places, L/F suffix or radix prefix. So 3._14, 110_L, 0x_123 are invalid and will cause compilation error.
  • Multiple underscores are allowed between digits, so 12___3 is a valid number.
  • You can’t put underscores at the end of literal. So 123_ is invalid and cause compile time error.
  • When you place underscore in the front of a numeric literal, it’s treated as an identifier and not a numeric literal. So don’t confuse with it.
  • You can’t use underscores where you are expecting a String with digits. For example Integer.parseInt("12_3"); will throw java.lang.NumberFormatException.

By admin

Leave a Reply

%d bloggers like this: