Coding with JDK7
- Using underscores in numerals.
- Diamond syntax used to work with collections + generics.
- Using Strings in switch statements.
- Making use of binary literals
Here is a short code sample that you can use to check the new features out. Use a plain text editor and your old friends javac and java, to test it out. IDEs will not support the new syntax and will most likely complain.
Sample JDK 7 Code:
public class Jdk7Tests {
public static void main(String[] args) {
Jdk7Tests jdk7Tests = new Jdk7Tests();
jdk7Tests.integersWithUnderscores();
jdk7Tests.stringSwitch();
jdk7Tests.binaryLiteral();
jdk7Tests.diamond();
}
private void integersWithUnderscores()
{
int i = 1_2;
System.out.println(i);
i*=10;
System.out.println(i);
int j=2_0;
System.out.println(i-j);
}
private void stringSwitch()
{
String key = "akey";
switch (key)
{
case "":
{
System.out.println("Nothing");
break;
}
case "akey":
{
System.out.println("Matched akey");
break;
}
default:
break;
}
}
private void binaryLiteral()
{
byte aByte = (byte)0b001;
short aShort = (short)0b010;
System.out.println(aByte + " " + aShort);
}
private void diamond()
{
Set<String> set = new TreeSet<>();
set.add("c");
set.add("b");
set.add("a");
for (String val : set)
{
System.out.println(val);
}
}
}
Underscores and numerals:
This feature will be great to process SSNs / phone numbers. No more putting the data into a String, parsing it, stripping it off underscores, and then putting it into an integer. But confusion arises when you try to do some arithmetic with the numeral. What is 1_2 * 2 ? The JVM strips the underscores when processing the operation as can be seen from the code example above. Thus 1_2 * 10 = 120 and 120 – 2_0 = 100. Simple
Diamond:
This should simplify instantiating collections. Time to update my auto complete code templates in anticipation of JDK 7. It is a little easier to read the code inside the diamond() method, in my opinion. Nothing more to the syntax though.
Switch with strings:
This is a pretty neat feature. You can now switch using Strings besides int, etc etc. Code that used to assign int variables to their corresponding String counterparts can now use this feature to simplify their code. Often code that contains call back methods in several places might set a int variable in one place, indicating that a particular String was found and then process this at a later point in time, using a switch construct. Some developers use this technique to write code that processes XML with SAX. They should be able to chop a few lines off that code using this feature.
Binary literals:
You can now use a binary literal representation and have that converted to a data type, say a byte or short, with very little code. I am not able to think of a scenario where I would use this regularly. But some of those coding practice problems that involve bits should be easier to write up .
(From www.certpal.com)