Version 7
of Java implements few very useful features known as a part of a project coin. I
agree, we need them and but changes to the language are pretty cosmetic. Closures
is the thing which all Java developers around the world expected, we have to be
patient, It will come up in version 8. But this is another story.
In this
post I want to show you what the direct language changes in Java 7 are.
1. STRINGS IN SWITCH
(number) {
case "One":
logger.info("Your number
is 1");
break;
case "Two":
logger.info("Your number
is 2");
break;
case "Three":
logger.info("Your number
is 3");
break;
case "Four":
logger.info("Your number
is 4");
break;
default:
logger.info("Error: wrong
number");
break;
}
2. BINARY LITERALS
int x = Integer.parseInt("1100110", 2);
int x1 =
0b1100110;
3. UNDERSCORES IN NUMBERS
long longNumber = 2_147_483_648L;
int binaryNumber =
0b0001_1100__0011_0111__0010_1011__1010_0011;
4. EXCEPTION HANDLING
try {
...
}
catch (FileNotFoundException | ParseException
|
ConfigurationException e) {
System.err.println("Config file
'"
+ fileName
+
"'
is missing or malformed");
}
5. DIAMOND SYNTAX
Don't need to evaluate generic types like in Java 6
Don't need to evaluate generic types like in Java 6
//JAVA 6
HashMap<String, String> hm1 = new HashMap<String, String>();
//JAVA 7
HashMap<String, String> hm2 = new HashMap<>();
try (FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));) {
String strLine;
while ((strLine = br.readLine()) != null) {
lines.add(strLine);
}
}
catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
}
catch (IOException e) {
logger.error("IOException", e);
}
7. GENERIC VARARGS WARN
This is small
change but also important. Compiler warn us on the compile time that we are
creating the array generic type which cannot be done type-safely.
public static <T> Collection<T> doSomething(T... entries) {
...
}
Now we can use new java annotation to let compiler not warn
us any more in this place : @SafeVarargs
References:
Brak komentarzy:
Prześlij komentarz