Log in
updated 11:29 AM UTC, May 4, 2016

Some neat Java 7 features which are used frequently

  • Written by Madhu V Rao
  • Published in Core Java

Some neat Java 7 features

  • Strings in Switch statement

 Till now Java could accept only char, byte , short, int , etc in a switch statement. But not anymore.

 

        switch (systemName) {
             case "linux":
                   seperator = "/";
             case "windows":
                   seperator = "\";
            case "mac":
                    seperator = "/";
            default:
                    System.out.println("Invalid Operating System!");
            break;
        }

Earlier to achieve the above code , we had to use series of if else statements.

As you can see the result now is a compact and neat code.

  •  Clubbing Exceptions in a catch block

In Java 7 , We can have exception handling done like this , if all the exceptions are handled  same way:

try {
         // some statements;
}catch (Exception1 e1 | Exception2  e2 )
{
         ex.printStackTrace();
}
  •  Try with resources block

With Java 7 , there is no need for us to handle opening and closing of resources in try and finally block. with the introduction of the try with resources block , Java does most of the stuff for us:

Let us see an example:

       try (BufferedReader in=new BufferedReader(new FileReader("file.txt")))
       {
            String line= null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

I haven't concentrated on the UI part of the Java 7 features, found out these are the features which are getting used more than other features. Please feel free to drop a comment if you feel I have missed out any important ones.


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest