There are several small new features and enhancements in Java 7. The major features and enhancements are in Java 8. Let’s look at the Java 7 new features. #1: string in switch statement:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
public class Java7Feature1 { private static String color = "BLUE"; private enum Color { RED, GREEN }; public static void main(String[] args) { // Pre Java 5 if (color.equals("RED")) { System.out.println("Color is Red"); } else if (color.equals("GREEN")) { System.out.println("Color is Green"); } else { System.out.println("Color not found"); } // Java 5 enum. try/catch is required for colours other than RED and GREEN try { switch (Color.valueOf(color)) { case RED: System.out.println("Color is Red"); break; case GREEN: System.out.println("Color is Green"); } } catch (IllegalArgumentException e) { System.out.println("Color not found"); } // Java 7 String in switch statement for simplicity & better readability //JDK 7 switch performs better than if-else //using types with enums is only useful when it serves a meaningful purpose //the value for color could come from database, and string in switch is handy for this switch (color) { case "RED": System.out.println("Color is Red"); break; case "GREEN": System.out.println("Color is Green"); break; default: System.out.println("Color not found"); } } } |
Output is:
|
1 2 3 4 |
Color not found Color not found Color not found |
#2 Binary integral literals
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Java7Feature2 { public static void main(String[] args) { // Pre Java 7 int n = Integer.parseInt("10000000", 2); System.out.println(n); n = 1 << 7; System.out.println(n); // Java 7 n = 0b10000000; // 128 = 2^7 System.out.println(n); } } |
Output:
|
1 2 3 4 |
128 128 128 |
#3: Underscores for better readability in...