Posts

Showing posts with the label JDK 7 Features

Learning JDK 7 Features Part 3: Try With Resource

Today we follow some standard coding conventions so that code should easy to read and maintainable or   i can say " Code should look beautiful  ". But there are some cases where we find our code is cluttered or duplicated. Its more often with Exception Handlers , Streams and JDBC  calls i.e. opening and closing streams/connections and multiple catch handlers. Java 7 comes to rescue us from this duplication and is succeeded in it. Before Java 7, to cloase a resource, we write a final block and close every resource in it. but some times the finally block become large and cluttered. Take a look at the code below:- finally { try { if (resultSet != null) resultSet.close(); } catch(Exception e) {} finally { try { if (statement != null) statement.close(); } ...

Learning JDK 7 Features Part 2: Updated Generic Instance Creation

Prior to Java 7, we create the generic instance as follows:- List<String> list = new ArrayList<String>( ); This syntex tunrs urgly in complex situations in which the length of type parameters increases. As mentioned in Effective Java (2nd Edition) chapter 2 , Joshua suggest us a way which can reduce the verbosity of generic instance creation; as follows public class TypeInference {                public static void main(String[ ] args)                     {                       List list = TypeInference.newInstance(); list.add("str");                     }        ...

Learning JDK 7 Features Part 1 : Strings in switch Statements

Switch statement is enhanced in JDK 7 with the support of String Object. Prior to it JDK 7 release, switch only supports  byte , short , char , and int   litearls. With this release onwards, we use string objects in switch expressions. Its is same as comparing String.equals method for each case. Please note the comparison is CASE- SENSITIVE.   Let see how it works :- private static String getTypeOfSeasonFromSwitch(String monthArg) { String typeOfSeason = null; switch (monthArg) { case "December": case "January": case "Febuary": typeOfSeason = "Winter"; break; case "March": case "April": case "May": typeOfSeason = "Spring"; break; case "June": case "July": case "August": typeOfSeason = "Summer"; b...