Java 7 Feature Underscores in Numeric Literals - Java @ Desk

Wednesday, August 20, 2014

Java 7 Feature Underscores in Numeric Literals

Java 7 Feature Underscores in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. You can groups of digits in numeric literals and readability of your code like you used to do it in schools.

Following are the valid ex :

int maxInteger = 0b0111_1111_1111_1111_1111_1111_1111_1111;
byte nybbles = 0b0010_0101;


You can place underscore only between numbers.

You cannot place underscore in following places

1. At the beginning or end of a number. Following placements are invalid and would lead to compilation error.

int x = _1; //beginning
int x1 = 1_; // end


2. Prior to an F or L suffix . Following placements are invalid and would lead to compilation error.

long y = 555_555_L 


3. Adjacent to a decimal point in a floating point literal. Following placements are invalid and would lead to compilation error.

float  z = 1._33F
float  z = 1_.33F


4. Radix Prefix of hex and binary literal Following placements are invalid and would lead to compilation error.

byte a = (byte) 0_b00000010; 
int a1 = 0_x1;


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.





No comments:

Post a Comment