New JDK 7 primer

Although I knew about the small language enhancements going into JDK7, named Project Coin, quite some time back it was only today that I got around to actually coding and trying them all out primarily due to prior laziness and poor editor support. Yes I know – there’s plenty of docs on Project Coin out there already. This is mine.
And now that JDK7 actually has a finite number of steps in its release schedule and is scheduled for release on 28/07/2011 we know our efforts in learning the new feature set are not going to waste and that very soon we’ll be able to write production code with this knowledge to make the industry a better place which is ultimately what is important.
Here I present a quick primer for the uninitiated. The small language enhancements going into JDK7 are as follows.

  1. Strings in switch
  2. Binary integral literals
  3. Underscores in numeric literals
  4. Multi-catch and more precise rethrow
  5. Improved type inference for generic instance creation(diamond)
  6. try-with-resources statement
  7. Simplified varargs method invocation

Compiling Java 7

JDK 7 : String in Switch

A long overdue and seemingly basic feature but better late than never. So now Java has the feature which dotNet had earlier.

public class StringsInSwitch {

public static void main(String[] args) {
for (String a : new String[]{"foo", "bar", "baz"}) {
switch (a) {
case "foo":
System.out.println("received foo!");
break;
case "bar":
System.out.println("received bar!");
break;
case "baz":
System.out.println("received baz!");
break;
}
}
}

}

Binary integral literals

I can’t say I’ve ever felt the absence of this rather unusual feature. Though it seems it was felt compelling enough to be added in. This is primarily a readability advantage – a semantic representation.

public class BinaryLiterals {

public static void main(String[] args) {

// An 8-bit 'byte' literal.
byte aByte = (byte) 0b00100001;

// A 16-bit 'short' literal.
short aShort = (short) 0b1010000101000101;

// Some 32-bit 'int' literals.
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' literal. Note the "L" suffix.
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

}

}

Underscores in numeric literals

I’ve often found myself adding javadoc to make a constant declaration clearer. This makes them somewhat clearer which is definitely helpful.

public class UnderScoredLiterals {

public static void main(String[] args) {

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

}

}

JDK7 : Improved type inference for generic instance creation(diamond)

Note the constructor inference which is new to Java 7 also.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericDiamondTypeInference {

static class MyClass <X> {
<Y> MyClass(Y y) {
}
}

public static void main(String[] args) {

// constructor inference
// <X> = <Integer>, <Y> = <String>
MyClass<Integer> myClass1 = new MyClass<>("");

// standard stuff
List<String> list = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();

}

}

Simplified varargs method invocation

This was a very tricky one to investigate. It’s still not clear what ‘simplified varargs method invocation’ is referring to but one difference (improvement) I was able to narrow down was that of a more specific and helpful warning that jdk7 adds to certain varargs code as below.

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class BetterVarargsWarnings {

static <T> List<T> foo(T... elements) {
return null;
}

static List<Map<String, String>> bar() {
Map<String, String> m = Collections.singletonMap("a", "b");
return foo(m, m, m);
}

}

More precise exception rethrow

The more precise rethrow is a tricky one to understand. See if you can spot what the new feature is in the example below. Will it compile on pre-java-7? If not how would it need to be changed to compile on pre-java-7? The answers lie after the example.

public class MorePreciseExceptionRethrow {

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

public static void main(String[] args) throws Exception1, Exception2 {
try {
boolean test = true;
if (test) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception e) {
throw e;
}
}

}

On Java 6 compiling the above gives the following exception.

Foo.java:18: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw e;
^
1 error

This can be fixed for Java 6 by changing:

public static void main(String[] args) throws Exception1, Exception2 {

to:

public static void main(String[] args) throws Exception {{

So now you see the improvement that Java 7 offers with this feature. You can be more precise in the declaration of the exceptions that you rethrow. Very nice indeed.

try-with-resources statement

This is simply beautiful and incredibly reassuring for the simple reason that resource closing is not only automatic and requires a lot less code but if in the examples below multiples exceptions are thrown (i.e. one in the closing of the resource and one in the use of the resource) then not only does the latter not get swallowed (unlike pre-java-7) but finally you can access all suppressed exceptions (i.e. the former) via the new API.

public class TryWithResources {

static class MyResource1 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("MyResource1 was closed!");
}
}

static class MyResource2 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("MyResource2 was closed!");
}
}

public static void main(String[] args) throws Exception {
/*
         * close() methods called in opposite order of creation
         */
try (MyResource1 myResource1 = new MyResource1();
MyResource2 myResource2 = new MyResource2()) {}
}

}

NOTE: In the above example the resources are closed in an order opposite to their order of creation.

Multi catch in Exceptions

The multi-catch is very useful indeed and significantly reduces the number of lines of code to do such things from before.

public class MultiCatchException {

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

public static void main(String[] args) {
try {
boolean test = true;
if (test) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception1 | Exception2 e) {
}
}

}

Null-safe Type in Java 7: New way to handle NullPointerException

Have you ever had an NPE or Null Pointer Exception in production? Or felt that handling null is a right pain? Well perhaps this Java 7 language change proposal – Null-ignore invocation – will interest you.
Though we can take pain, like checking whether that value is null and then further doing checks to ensure all sorts of ways to handle NPE, Java is offering “null safe method invocation” to handle the same.
This operator is ?.
Consider the following code:
Eg. Consider the following code:

public String getName(Person person) {
return person.getName()
}

Now if person is null we will get NPE. So to avoid it we have to check :

public String getPostcode(Person person) {
if(person!=null)
return person.getName();
else return String.Empty;
}

or you may return null to say that person is null. But empty string preferred.

Till this level its fine, suppose you have to use nesting of 2 getters, like:

public String getGrandFatherName(Person person) {
return person.getFather().getFather()
}

So here you have to check 2 times for null:

public String getGrandFatherName(Person person) {
if (person != null) {
Person father = person.getFather();
if (father != null) {
Person grandFather = father.getFather;
if(grandFather != null)
return grandFather.getName();
}
}
return null;
}

So rather than handling these complications, we can get away with ?. operator.

return person?.getFather()?.getFather()?.getName();

This code is null-safe and won’t throw NPE. But the main improvement is readability of code.

So what does “?.” does?

This proposal aims to tackle this by adding compiler syntax sugar to generate the null pointer checks for developers. It achieves this by adding an alternative to the dot for method and field invocation – ?. Using this invokes a method or field in the same way as using the dot, but with one change. If the expression on the left hand side of the hash is null, then the result of the expression is null. If the expression type is a primitive then zero or false is returned instead of null. If the expression is a void, then no action occurs. 

Refer java complete reference for more on java :

http://rcm.amazon.com/e/cm?t=javaj07-20&o=1&p=8&l=bpl&asins=0071606300&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr