Underscores in Numeric Literals - Java Language Basics

Java examples for Language Basics:Primitive Types

Introduction

Java can use underscores between two digits in numeric literals.

For example, an int literal 1969 can be written as 1_969, 19_69, 196_9, 1___969.

The use of underscores is allowed in octal, hexadecimal, and binary formats.

The following examples show the valid uses of underscores in numeric literals:

int x1 = 2_969;            // Underscore in deciaml format 
int x2 = 1__929;           // Multiple consecutive underscores 
int x3 = 03_661;           // Underscore in octal literal 
int x4 = 0b0111_1011_0001; // Underscore in binary literal 
int x5 = 0x7_B_1;          // Underscores in hexadecimal literal 
byte b1 = 2_2_7;           // Underscores in decimal format 
double d1  = 1_969.09_19;  // Underscores in double literal 
  

Underscores are allowed in numeric literals only between digits.

The following examples show the invalid uses of underscores in numeric literals:

int y1 = _123;         // An error. Underscore in the beginning 
int y2 = 1239_;         // An error. Underscore in the end 
int y3 = 0x_7B1;        // An error. Underscore after prefix 0x 
int y4 = 0_x7B1;        // An error. Underscore inside prefix 0x 
long z1 = 123_L;       // An error. Underscore with suffix L 
double d1 = 123_.0919; // An error. Underscore before decimal 
double d1 = 123._0919; // An error. Underscore after decimal

Related Tutorials