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

Java 7 : Use Switch With String

In the JDK 7 release, you can use a String object in the expression of a switch statement.

Comparing string object is case sensitive.

   1: public class TEST {
   2:  
   3:     public static void testSwt(String testswitch) {
   4:         String tw;
   5:         switch (testswitch) {
   6:             case "teststr":
   7:                 tw = "TestingSwitch with String";
   8:                 break;
   9:             case "testswitch2":
  10:                 tw = "Testing Switch with String one";
  11:                 break;
  12:             case "testswitch3":
  13:                 tw = "Testing Switch with String two";
  14:                 break;
  15:             default:
  16:                 tw = "ERROR";
  17:                 break;
  18:         }
  19:         System.out.println(tw);
  20:  
  21:     }
  22:  
  23:     public static void main(String[] args) {
  24:         String strswitch = "teststr";
  25:         TEST.testSwt(strswitch);
  26:  
  27:     }
  28: }

The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Java 7: Project Coin

Project Coin is to determine what set of small language changes should be added to JDK 7.

Language Changes

binary literals
strings in switch
try-with-resources
diamond operator
multi-catch with final rethrow
safe var-args annotation

IDE Support for Project Coin.

IntelliJ IDEA 10.5 and later

Eclipse 3.7.1 and later

NetBeans 7.0 and later