Java 7 Numeric Literals with Underscore

Numeric Literals

Java 7 provides the facility to use underscore in numeric literals like int, byte, short, float, long, double. We can use any number of underscore characters (_) between digits in a numerical literal. It helps to improve the code readability. Note:

  • Underscores cannot be put at the end of literal. So 12_ is invalid and cause compile time error.
  • When we place underscore in the front of a numeric literal, it’s treated as an identifier and not a numeric literal.

Java numeric literals with underscore example

package com.w3schools;

public class Java7UnderscoreInNumericLiteral {
	public static void main(String args[]){
		//Underscore in integral literal  
        int a = 10_000;  
        System.out.println("a = "+a);  
        //Underscore in floating literal  
        float b = 30.5_000f;  
        System.out.println("b = "+b);  
        //Underscore in binary literal  
        int c = 0B10_10;  
        System.out.println("c = "+c);  
        //Underscore in hexadecimal literal  
        int d = 0x1_1;  
        System.out.println("d = "+d);  
        //Underscore in octal literal  
        int e = 01_1;  
        System.out.println("e = "+e);  


a = 10000
b = 30.5
c = 10
d = 17
e = 9
Please follow and like us:
Content Protection by