About Me

My photo
I know the last digit of PI

Friday, August 26, 2011

Java 7 - project coin

Java 7 language syntax changes in nutshell (Project coin).


  • Strings in switch

  • Binary integral literals and underscores in numeric literals

  • Multi-catch and more precise rethrow

  • Improved type inference for generic instance creation (diamond)

  • try-with-resources statement

  • Simplified varargs method invocation





Strings in switch


public static boolean getBoolean(String s) { 

switch(s.toLowerCase()) {
case "true" : return true;
case "false" : return false;
default: throw new IllegalArgumentException("Invalid value. Only strings 'true' and 'false' are acceptable");
}
}


Binary integral literals and underscores in numeric literals



public static final int binaryNumber = 0b11111111_11111111;// 65535
public static final int hexNumber = 0xFF_FF;// 65535


Multi-catch and more precise rethrow



Multi-catch



try {
Class<?> c = Class.forName("java.lang.String");
Object o = c.newInstance();
Method m = c.getMethod("length");
System.out.println("Length = " + m.invoke(o));
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException
| InvocationTargetException | IllegalArgumentException | NoSuchMethodException ex ) {
ex.printStackTrace();
}


ReflectiveOperationException



try {
Class<?> c = Class.forName("java.lang.String");
Object o = c.newInstance();
Method m = c.getMethod("length");
System.out.println("Length = " + m.invoke(o));
} catch (ReflectiveOperationException ex ) {
// Now all reflection exception have super class ReflectiveOperationException
ex.printStackTrace();
}


more precise rethrow



public static class Exception1 extends Exception {}
public static class Exception2 extends Exception {}

public void morePreciseExceptionRethrow() throws Exception1, Exception2 {
try {
if (1==2) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception ex) {
// here the compiler knows that only Exception1 and Exception2 are thrown from the code above. In JDK 1.6 you need to declare that the method is throwing Exception, but in JDK 1.7 you may declare only the exceptions really thrown.
throw ex;
}
}


Improved type inference for generic instance creation (diamond)



List list = new ArrayList<>();
Map> map = new TreeMap<>();


try-with-resources statement



public void copy(String srcFileName, String destFileName) throws IOException {
try(InputStream in = new FileInputStream(srcFileName); OutputStream out = new FileOutputStream(destFileName)){
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) != -1) {
out.write(buff, 0, n);
}
}
// here the in and out are closed
}



Simplified varargs method invocation


More details