Underscores in Numeric Literals – Java 7 Feature

Filed Under: Java

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:


package com.journaldev.util;

public class UnderscoreNumericLiterals {

	public static void main(String[] args) {
		long ccNumber = 1234_5678_9012_3456L;
		long ssn = 999_99_9999L;
		float pi = 	3.14_15F;
		long hexadecimalBytes = 0xFF_EC_DE_5E;
		long hexadecimalWords = 0xCAFE_BABE;
		long maxOfLong = 0x7fff_ffff_ffff_ffffL;
		byte byteInBinary = 0b0010_0101;
		long longInBinary = 0b11010010_01101001_10010100_10010010;
		int add = 12_3 + 3_2_1;
		System.out.println("ccNumber="+ccNumber);
		System.out.println("ssn="+ssn);
		System.out.println("pi="+pi);
		System.out.println("hexadecimalBytes="+hexadecimalBytes);
		System.out.println("hexadecimalWords="+hexadecimalWords);
		System.out.println("maxOfLong="+maxOfLong);
		System.out.println("byteInBinary="+byteInBinary);
		System.out.println("longInBinary="+longInBinary);
		System.out.println("add="+add);
	}

}

The above program compiles fine and here is the output:


ccNumber=1234567890123456
ssn=999999999
pi=3.1415
hexadecimalBytes=-1253794
hexadecimalWords=-889275714
maxOfLong=9223372036854775807
byteInBinary=37
longInBinary=-764832622
add=444

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.
    
    int _10=0;
    int x = _10;
    
  • You can’t use underscores where you are expecting a String with digits. For example Integer.parseInt("12_3"); will throw java.lang.NumberFormatException.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages