Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

New syntax of Java 7 (Project Coin)

The project idea was to add small changes in language, without having to depend on other projects, and without forcing developers to join the new syntax.

Project coin is one of the projects that were developed for the implementation of Java 7.

The project idea was to add small changes in language, without having to depend on other projects, and without forcing developers to join the new syntax.

After several suggestions, was chosen about five modifications:

* Ability to use strings in switch
* Try-to-resources & Multi-catch
* Improvement in the creation of objects using generics (diamond)
* Simplify methods with variable number of arguments.
* Support for dynamic languages JSR 292

In this tutorial I will (try to) explain the use of the new syntax of the first three items on the list.

(The last two are very specific to your area, more information about them can be found in their links)

Strings in switch

The operator switch until the previous versions only supported types char, byte, short, int, Character, Byte, Short, Integer or enums.

In the new version, it is also possible to use Strings. Before, the only way was to make chains of if-else, for example:

String string = //anything  

  

if(string.equals("one"){  

} else if(string.equals("two"){  

  

}  else if(string.equals("three"){  

    

}  else if(string.equals("four"){  

     

} else {  

  //default  

}  



In  java 7 this same piece of code can be written with a switch:

 

String string = //anything

switch(string){  

case "one":   

              //one  

              break;  

case "two":   

              //two 

              break;  

case "three":   

              //three 

              break;  

case "four":   

              //four

              break;  

default :  

             //default  

}  

 

try-with-resources

It was created a new interface: AutoCloseable. All classes that implement (directly or indirectly) this interface are considered to be resources and have to be flushed (. Close ()) after use.

With the new try, it is possible that these resources are automatically closed  after the execution of the block (either for normal execution or exception).

An example of code that can be modified to use the new feature is this: a method that makes a query to the database, and uses a statement as a resource:

public static void viewTable(Connection con) throws SQLException {  

 

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";  

   Statement stmt;  

  try{  

     stmt = con.createStatement();  

     ResultSet rs = stmt.executeQuery(query);  

 

     while (rs.next()) {  

       String coffeeName = rs.getString("COF_NAME");  

       int supplierID = rs.getInt("SUP_ID");  

       float price = rs.getFloat("PRICE");  

       int sales = rs.getInt("SALES");  

       int total = rs.getInt("TOTAL");  

      System.out.println(coffeeName + ", " + supplierID + ", " + price +  

                          ", " + sales + ", " + total);  

     }  

 

   } catch (SQLException e) {  

     e.printStackTrace(System.err);  

   } finally {  

      stmt.close();  

   }  

 

 }  

 

The above code has two problems:

First, you need a finally block to ensure that the resource was released.

Second, if the finally block also throw an exception, after the try block being interrupted by an exception (which is possible though rare) this exception will override the previous exception.

With the new try-with-resources, both problems are solved! the code would look like:

 

public static void viewTable(Connection con) throws SQLException {  

 

   String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";  

   Statement stmt;  

   try(Statement stmt = con.createStatement()){       

     ResultSet rs = stmt.executeQuery(query);  

 

     while (rs.next()) {  

       String coffeeName = rs.getString("COF_NAME");  

       int supplierID = rs.getInt("SUP_ID");  

       float price = rs.getFloat("PRICE");  

      int sales = rs.getInt("SALES");  

       int total = rs.getInt("TOTAL");  

       System.out.println(coffeeName + ", " + supplierID + ", " + price +  

                          ", " + sales + ", " + total);  

     }  

 

   } catch (SQLException e) {  

     e.printStackTrace(System.err);  

   }  

}  

 

The resource (in this case a statement) is started in parentheses after the keyword try. The local variable stmt is implicitly final, and has scope within the try block.

When the block is finished (in a normal or exception) the resource will be automatically closed. Any exceptions thrown in the act of releasing the resource will be removed, and the original exception is maintained.

Other exceptions that have been released can be retrieved by Throwable.getSuppressed ()

Several resources can be started at the same try; in this case they must be separated by a semicolon ";" and will be closed in reverse order to which they are declared.

Multi-catch

A single catch can now contain several different types of exceptions.
Consider the following code, which changes the look and feel of the application:

try {  

       // Set cross-platform Java L&F (also called "Metal")  

        UIManager.setLookAndFeel(  

            UIManager.getCrossPlatformLookAndFeelClassName());  

    }   

    catch (UnsupportedLookAndFeelException e) {  

       // handle exception  

    }  

    catch (ClassNotFoundException e) {  

       // handle exception  

    }  

    catch (InstantiationException e) {  

       // handle exception  

    }  

    catch (IllegalAccessException e) {  

       // handle exception  

    }  

As the method can throw several different exceptions, you need multiple catch blocks. (or just one, using a generic exception)

With multi-catch all exceptions can be placed in the same catch, separated by a vertical bar "|"

 

try {  

       // Set cross-platform Java L&F (also called "Metal")  

        UIManager.setLookAndFeel(  

            UIManager.getCrossPlatformLookAndFeelClassName());  

    }   

    catch (UnsupportedLookAndFeelException|ClassNotFoundException|InstantiationException|

               IllegalAccessException e) {  

       // handle exception  

    }  

 

Creation of new objects with generics


This is a very simple update. instead of to declare the generic type twice (once in the declaration of the variable, and again in the object creation), it is now possible to declare only in the type variable, and create the object with /span>> empty (diamond). The type of object created will follow the variable type.

For example, this code can be rewritten

     ArrayList strings = new ArrayList ();
     HashMap buttons = new HashMap ();
     Map /span>String, List > anagrams = new HashMap /span>String, List > ();


using the new syntax, the same code looks like

     ArrayList strings = new ArrayList
     Buttons = new HashMap HashMap
     Map /span>String, List > anagrams = new HashMap


Conclusion
These new changes in the language does not necessarily require the developers to use, however, bring new resources and facilities and should be leveraged to create a leaner code, readable and functional.

 



MrBool is a totally free website made for software developers. Our articles and courses are totally free with focus on useful techniques and best practices

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login