dcsimg

Java SE 7 New Features and Code Examples

Java SE 7 included multiple core language enhancements. We look at these new additions and provide some Java code samples that you can program along with. These samples can be used to learn and understand the features discussed in this article.

Read the previous part of this series, history of Java: Core 6 Features.

Below is a list of Java SE 7 release details and new features introduced into the 7th iteration of the language.

Java SE 7 Release Details

  • Java SE 7 Release Date: 28-07-2011
  • Java SE 7 Code Name: Dolphin

Java SE 7 New Feature List

  • Introduction of an improved type inference for generic instance creation, also known as the diamond operator or <>.
  • Addition of strings in switch statements.
  • try statements now have automatic resource management.
  • A simplified varargs method declaration was introduced.
  • The addition of binary integer literals.
  • Underscores in numeric literals are now allowed.
  • The ability to catch multiple exception types and rethrow exceptions with improved type checking.

Java 7 Diamond Syntax (Type Inference for Generics)

Using generics in our applications often leads developers with very long lines of code in our software and modules. This causes a lot of confusion and lead to poor readability - something we definitely want to avoid in our code. The reason for this was that there might be multiple generic types that were used in the same line of code.

To fix this potential problem, Java 7 introduced the concept of the diamond operator - or diamond syntax. Using this, developers could infer the type of the generic variable. This improved the situation and readability of Java code by reducing the length of the line of code (to a certain extent at any rate). Here is an example of the diamond operator and diamond syntax in Java:

 
 public class java7_DiamondSyntax {   
    public static void main(String[] args) {        
       Map<String, Map<String, List>> list = new HashMap<>();   
       List aList = new ArrayList();   
       aList.add("09.10");   
       aList.add("09.20");   
       aList.add("09.22");   
       Map<String,List> iMap = new HashMap<>();   
       iMap.put("radiac", aList);   
       list.put("radia", iMap);   
    }   
  }   

Multiple Exception Handling in Java

Prior to Java 7, in order to catch more than one exception in a block you had to create a catch block for each of the checked exceptions. Oftentimes a developer may want to perform a similar action for many exceptions that are very similar or that share a similar exception flow and execution. This is the utility of the new multiple exception handling feature.

To better understand how multiple exception handling in Java works, execute the code below directly in Eclipse or your Java IDE:

  public class java7_ExceptionHandling {   
   
    public static void main(String[] args) {   
       try {           
         Integer value = Integer.parseInt("ABC");   
         File file = new File("exception.txt");   
         FileReader fileReader = new FileReader(file);           
       } catch(NumberFormatException | FileNotFoundException foe) {   
         System.out.println("Multiple Exception Types");   
       }   
    }   
  }   

Binary Literals and Underscores in Literals using Java

Continuing on the subject of readability for numeric literals, the concept of using an underscore is to provide separate numeric literals. For example, at the thousandth place, millionth place, hundredth place, and so on. Also, binary literals are allowed in Java 7, beginning with 0b.

All types of numeric literals will allow the use of '_'. Developers need to make sure that '_' is not used as the before first or after last digit of the numeric literal and '_' is not used adjacent to the decimal point, and that '_' is used before the F or the Lsuffix.

Here is an example of the above in Java code:

  
public class java7_Literals {   
    int million = 100_000_000;   
    byte b = (byte) 0b0001111111;   
    short s = (short) 0b111100000000;    
    int i = 0b11111111111111111111;   
   
    public static void main(String[] args) {   
   
       java7_Literals l = new java7_Literals();   
       System.out.println(l.million);   
       System.out.println(l.b + ":" + l.s + ":" + l.i);   
    }   
  }   

Strings in Switch Statements with Java

With the release of Java 7, developers could begin using strings in their switch statements - a very powerful tool indeed. Prior to this, the alternative would have been to use a series of if statements with an equals() comparison.

Here is how you use strings in switch statements with Java:

 public class java7_StringSwitch {   
    static String day = "SAT";   
   
    public static void main(String[] args) {   
       switch(day) {   
         case "MON": { System.out.println("Monday"); break; }   
         case "TUE": { System.out.println("Tuesday"); break; }   
         case "SUN": { System.out.println("Sunday"); break; }   
         case "SAT": { System.out.println("Saturday"); break; }   
       }   
    }   
  }   


 

Try With Resources using Java

After Java 7 was released, it became possible to use and create a resource within a try block and, further, use it within the enclosing block. This is applicable to all objects and resources that use java.io.Closeable. Automatically, upon encountering an exception - or if there is no exception equal to or greater than ( =>) the developer is guaranteed that the close() method will be called by runtime once it is 'outside’ of the context of the try block.

Here is some code further showcasing this:

 public class java7_TryWithResources {   
   
    public static void main(String[] args) throws IOException {        
       try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {   
         br.readLine();   
       } finally {   
         System.out.println("All Resources Closed.");   
       }   
    }   
  }   

Note: Make sure that you have file.txt in your classpath.

We will look at features and example code from Java 8 in our next part in this series. Stay tuned!

[GitHub Repository for Code Samples] https://github.com/sumithpuri/skp-code-marathon-bangkok