Unlike Java 6, This time there were couple Java Programming Language Enhancements in Java SE 7.
Here see below couple of intersting enhancements.
- Strings in switch
- Try-with-resources statement
- Diamond syntax for constructors
- Multi-catch and more precise rethrow
Let's see more in detail the first enhancement.
Strings in switch
switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements.
Syntax:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
Until Java SE 6, The expression must be of type byte, short, int, or char only; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal.
Now in Java SE 7, you can use a String object in the expression of a switch statement. The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.
The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Example:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
Let's discuss about the other enhancements in my next blog.