Java 7: Underscores in numeric literals

  Java Features     Java 5     Java 7     Java 8  
Java 7 features
 Binary literals |   Strings in switch statements |   Catching multiple exceptions |   Try with resources |   Type inference |   Underscores in numeric literals |   By date 

The underscores in numeric literals is included in JSE7. You can use the underscore character between digits in a numerical literals similar to a comma or a space as a separater. This feature is used to improve the readability of the code. For more info click here to read Oracle’s explanation.

Notice: Underscores have to be located within digits. The positions of the following underscores are not allowed.

int i = 3553_;
int i2 = _434;
long l = 948948298_L;
long l2 = 83473843L_
float f = 454._34;
float f2 = 65_.56;

Example 1: Underscores in numeric literals code

What is the output of the following code?

public class NumericUnderscore
{
  public static void main(String[] args)
  {
    long bankAccountNumber = 4532_3457_9887L;
    float area = 3460.95_64F;
    long hexCode = 0xA0B_0D;
    byte bt = 0b0010_0101;
    int i = 8_484_923;
    System.out.println(bankAccountNumber);
    System.out.println(area);
    System.out.println(hexCode);
    System.out.println(bt);
    System.out.println(i);
  }
}
Author: Sar Maroof

Answer explanation

  1. bankAccountNumber = 4532_3457_9887L
  2. area = 3460.95_64F
  3. hexCode = 0xA0B_0D = (10 x 16⁴) + 0 + (11 x 16²) + 0 + (13 x 16⁰) = 658189
  4. binary = 0b10_0101 = 2⁵ + 0 + 0 + 2² + 0 + 2⁰ = 32 + 4 + 1 = 37
  5. i = 8_484_923

The correct answer is:
453234579887
3460.9563
658189
37
8484923





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *