Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

SKP's Java/Java EE Gotchas: Revisiting Java SE 7 Features!

DZone's Guide to

SKP's Java/Java EE Gotchas: Revisiting Java SE 7 Features!

As we near the present, let's remember what Java 7 brought to the table, namely Strings in switch statements, multiple exception handling, and binary integer literals.

· Java Zone ·
Free Resource

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

GitHub Link (Code Samples from the Article & More)
https://github.com/sumithpuri/skp-code-marathon-bangkok


Preparing for an interview? Want to just revisit Java SE 7 features? Trying to recollect or revise a Java SE programming construct? Let me take you back in time to what was introduced first in Java SE 7? Join me for this tutorial series on Java as we all eagerly await the official release of Java SE 9! 

Java SE 7 Release Date: 28-07-2011

Java SE 7 Code Name: Dolphin


Java SE 7 Highlights 

  • Strings in switch statements.

  • Automatic resource management in try statements.

  • Improved type inference for generic instance creation, AKA the diamond operator <>.

  • Simplified varargs method declaration.

  • Binary integer literals.

  • Allowing underscores in numeric literals.

  • Catching multiple exception types and rethrowing exceptions with improved type checking.

I have provided some of the most important core language enhancements for JDK 7.0, along with code samples. The examples provided below can be directly pasted into your IDE, and you may name the class as provided.

Strings in Switch Statements

You may use Strings in your switch statements, which is a powerful tool. The alternative would have been to use a series of if statements with an .equals() comparison. You may directly execute the code below in Eclipse to understand it better.

 public class jdk7_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; }  
           }  
      }  
 }  


Multiple Exception Handling 

Before JDK7, you would have to catch multiple exceptions in a block — with a catch block for each of the thrown checked exceptions. But sometimes you may want to take actions for many exceptions that are similar or the same. Hence, the utility of this feature. You may directly execute the code below in Eclipse to understand it better.

 public class jdk7_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");  
           }  
      }  
 }  


Try With Resources

You may use/create a resource withing the try block, from JDK7, and use it within the following block. This includes all objects/resources that implement java.io.Closeable. Automatically, on encountering the exception or if there is no exception, the close() method is guaranteed to be called by the runtime.

 public class jdk7_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.");  
           }  
      }  
 }  


Make sure that you have a file.txt in your classpath.

Diamond Syntax (Type Inference for Generics) 

Sometimes when we are using generics in an application, we may end up with a long line of code, which may be very confusing or have poor readability. This is because there may be multiple generic types that are used in the same line. To improve upon this, JDK7 introduces the concept of the diamond operator or diamond syntax, where the type of the generic variable is inferred.

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


Binary Literals, Underscore in Literals  

Continuing on the aspects of readability for numeric literals, the concept of the underscore is provided to separate numeric literals — like at the thousands place, millions place, hundreds place, etc. Also, Binary Literals are allowed in JDK7, starting with 0b. All types of numeric literals will allow the use of '_'. You have 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 '_' is used before the F or the L suffix.

 public class jdk7_Literals {  
      int million = 100_000_000;  
      byte b = (byte) 0b0001111111;  
      short s = (short) 0b111100000000;   
      int i = 0b11111111111111111111;  

      public static void main(String[] args) {  

           jdk7_Literals l = new jdk7_Literals();  
           System.out.println(l.million);  
           System.out.println(l.b + ":" + l.s + ":" + l.i);  
      }  
 }  


Happy times with JDK 7!

Ready Reference on DZone

 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

Topics:
java ,try-with-resource ,diamond operator ,type checking ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}