Wednesday, December 14, 2011

Java 7 : Using Underscore in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. It can improve the readability of your code.

   1: public class TEST {
   2:  
   3:     static byte testByte = 0b0011_0101;
   4:     static long testLong = 333_2222_2222L;    
   5:     static int testInt=100_000;
   6:  
   7:     public static void main(String[] args) {
   8:         System.out.println(testByte);
   9:         System.out.println(testLong);        
  10:         System.out.println(testInt);        
  11:     }
  12: }

Allowed

we can place underscores only between digits

Not Allowed

we cannot place underscores in the following places:


  • At the beginning or end of a number  (_54 , 54_)
  • Adjacent to a decimal point in a floating point literal  (1._22)
  • Prior to an F or L suffix  (2.33_F)
  • In positions where a string of digits is expected

No comments:

Post a Comment