Java @ Desk: Java 7 | Java at your desk

Java 7 Feature Underscores in Numeric Literals

Java 7 Feature Underscores in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. You can groups of digits in numeric literals and readability of your code like you used to do it in schools.

Following are the valid ex :

int maxInteger = 0b0111_1111_1111_1111_1111_1111_1111_1111;
byte nybbles = 0b0010_0101;


You can place underscore only between numbers.

You cannot place underscore in following places

1. At the beginning or end of a number. Following placements are invalid and would lead to compilation error.

int x = _1; //beginning
int x1 = 1_; // end


2. Prior to an F or L suffix . Following placements are invalid and would lead to compilation error.

long y = 555_555_L 


3. Adjacent to a decimal point in a floating point literal. Following placements are invalid and would lead to compilation error.

float  z = 1._33F
float  z = 1_.33F


4. Radix Prefix of hex and binary literal Following placements are invalid and would lead to compilation error.

byte a = (byte) 0_b00000010; 
int a1 = 0_x1;


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Binary Literals



Binary Literals

In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number.





The following examples show binary literals:

byte x = (byte) 0b00000010; // 8 –bit Binary
short y = (short) 0b0000000000000101; //16 - bit Binary
String z = Integer.toBinaryString(2147483647);
int z1 = Integer.parseInt(Integer.toBinaryString(2147483647), 2);
int a = 0B100; // The B can be upper or lower case.

System.out.println("value of X:" + x);
System.out.println("value of Y:" + y);
System.out.println("value of Z:" + z);
System.out.println("value of Z1:" + z1);
System.out.println("value of A:" + a);


value of X:2
value of Y:5
value of Z:1111111111111111111111111111111
value of Z1:2147483647
value of A:4


Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by two bit:

public static final int[] phases = {
  0b00110001,
  0b11000100,
  0b00010011,
  0b01001100
}


In hexadecimal, the relationship among the numbers is not readily apparent:

public static final int[] phases = {
  0x31, 0xC4, 0x13, 0x4C
}


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Java 7 Feature Switch in String

Java 7 Feature Switch in String

Switch statement worked on byte, short, char, and int primitive data types and enum. It took us about 16 years to realize that java.lang.String is also a constant and add it to the list of data types supported by a switch statement

The switch statement transfers control to one of several statements depending on the value of an expression.

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.

The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

All of the following must be true, or a compile-time error occurs:

1. Every case constant expression associated with a switch statement must be assignable to the type of the switch Expression. i.e a String switch cannot have case with expression value to be int or something else.
Type mismatch: cannot convert from int to String.


Note: The type of the Expression must be char, byte, short, int, Character, Byte,
Short, Integer, String, or an enum type, or a compile-time error occurs.


2. No two of the case constant expressions associated with a switch statement may have the same value.
Duplicate case error is thrown


3. No switch label can be null.
case expressions must be constant expressions


4. At most one default label may be associated with the same switch statement.
default case already defined


5. When the switch statement is executed, first the Expression is evaluated. If the Expression evaluates to null, a NullPointerException is thrown and the entire switch statement completes abruptly for that reason. Otherwise, if the result is of a reference type, it is subject to unboxing conversion

6. Empty String "" can be added as a case expression.

7. Case check are case sensitive

8. In order for the NSwitch example to accept any fruit regardless of case, fruit name is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase.

9. If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly for some reason, the switch statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the Expression with each case constant, and there is a choice:

9.1. If one of the case constants is equal to the value of the expression, then we say
that the case matches, and all statements after the matching case label in the switch
block, if any, are executed in sequence.

9.2. If all these statements complete normally, or if there are no statements after
the matching case label, then the entire switch statement completes normally.

9.3. If no case matches but there are a default label, then all statements after the
matching default label in the switch block, if any, are executed in sequence.

9.4. If all these statements complete normally, or if there are no statements after the
default label, then the entire switch statement completes normally.

9.5. If no case matches and there is no default label, then no further action is taken
and the switch statement completes normally.




public class NSwitch {
 
  public static String getColor(String name) {
          if(name== null){
   return "Unknown";
   }   
switch (name.toLowerCase()) {
   case "apple":
   case "cherry":
   case "strawberry":
   return "Red";
   case "banana":
   case "papaya":
   return "Yellow";
   case "kiwi":
   case "grapes":
   case "guava":
   return "Green";
   case "clementine":
   case "persimmon":
   return "Orange";
   default:
   return "Unknown";
   }
   
  } 

  public static void main(String[] args) {
  getColor("apple");
 }
}


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Rethrowing Exceptions with More Inclusive Type Checking

Rethrowing Exceptions with More Inclusive Type Checking

With Java SE 7, you can throw more precise exception, i.e. you can actually throw an exception type which a try block can throw.

The exception thrown in the catch clause can be different than the one which is declared in the method signature.

Method declaration can throws more precise exception type.


Consider the following example

public static void invalidRethrow() throws Exception {
 try {
  URL url = new URL("invalidurl");
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(url.openStream()));
     String line = reader.readLine();
     SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
     Date date = format.parse(line);
 } catch (Exception e) {
  System.out.println("Caught exception: " + e.getMessage());
  throw e;
 }
} 


This examples's try block could throw either IOException or ParseException.

Suppose you want to specify these exception types in the throws clause of the invalidRethrow method declaration. It would have lead to compilation error because the exception parameter of catch clause is of type Exception. In releases prior to Java 7, you can only specify the exception type Exception in the throws clause of the invalidRethrow method declaration.

However, in Java 7, you can specify the exception types IOException and ParseException in the throws clause in the invalidRethrow method declaration. The Java 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be IOException and ParseException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either IOException or ParseException:

public static void invalidRethrow() throws IOException, ParseException {
 try {
  URL url = new URL("invalidurl");
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(url.openStream()));
     String line = reader.readLine();
     SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
     Date date = format.parse(line);
 } catch (Exception e) {
  System.out.println("Caught exception: " + e.getMessage());
  throw e;
 }
} 


Caught exception: no protocol: invalidurl
java.net.MalformedURLException: no protocol: invalidurl
 at java.net.URL.<init>(URL.java:585)
 at java.net.URL.<init>(URL.java:482)
 at java.net.URL.<init>(URL.java:431)
 at Exception.test.rethrowEx (test.java:61)
 at Exception.test.main(test.java:52)


The compiler verifies that the type of the rethrown exception meets the following conditions:

1. The try block is able to throw it. i.e. catch cannot throw any other exception which is not declared. It will give compilation error Unhandled exception type Exception
2. There are no other preceding catch blocks that can handle it.
3. It is a subtype or supertype of one of the catch clause's exception parameters.



Previously, you cannot throw an exception that is a supertype of one of the catch clause's exception parameters. A compiler from a release prior to Java SE 7 generates the error, "unreported exception Exception; must be caught or declared to be thrown" at the statement throw e.

The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowEx() method declaration.

However, the type of the catch parameter e is Exception, which is a supertype, not a subtype, of IOException and ParseException.

Note: You can use multi-catch here too in the catch clause to be more precise.

public static void rethrowEx() throws IOException, ParseException{
 try {
  URL url = new URL("invalidurl");
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(url.openStream()));
     String line = reader.readLine();
     SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
     Date date = format.parse(line);
 } catch (IOException | ParseException e) {
  System.out.println("Caught exception: " + e.getMessage());
  throw e;
 }
}


The exception handling changes in Java SE 7 allows you not only to write more crisp code by using its multi-catch feature but also allows you to let your bubble up your original exception by allowing you to re-throw it.

This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Java SE 7 Exception Handling

Java SE 7 Exception Handling

Multi-Catch Exceptions

Multi- catch has been added to reduce the redundant code, to make the code more concise and clear. Moreover, it makes the exception handling easier.

Consider below example. Assume that you have bind the parameter and create a in your application. This class holds a value that can be used in a JDBC statement. This will ensure that your values get converted correctly and stored properly in the underlying DB.

public static Parameter getParameter(String fieldType,  String fieldValue){          
 try {
  // Code goes here
 } catch (ParseException ne){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, ne);
 } catch (NumberFormatException ne){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, ne);
 } catch (IllegalArgumentException iae){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, iae);   
 }
 return p;
}


If you wanted to have the same logic for two of the three cases above, say, the ParseException and the IOException, you had to copy and paste the same code.

Unless you are lazy programmer to code as shown below:

public static Parameter getParameter(String fieldType,  String fieldValue) {
        try {
  // Code goes here
        } catch(Exception e){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, e);
 }
        return p;
}


Any code in the try block could throw an exception that would be swallowed up with a blanket (Exception) catch clause. If an exception that is not a ParseException or IllegalArgumentException is thrown (for example, a IOException, LoginException), the code would still catch it, but the upstream user would not be aware of what really happened.

Swallowing up an exception like that makes problems difficult to debug. Below example shows how to properly combine the two statements into one catch block. Notice the syntax for the catch clause (NumberFormatException | IllegalArgumentException). This catch clause will catch both NumberFormatException and IllegalArgumentException.

So, now we can share the same exception handling code for two different exceptions you can use the pipe syntax as shown below:

Syntax: 
(ExceptionType| ... | ExceptionType variable).


public static Parameter  getParameter(String fieldType,  String fieldValue) {
        try {
 } catch (ParseException | IllegalArgumentException  ne){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, ne);
 }
 return p;
}


If you notice in the above code, you are missing a catch for NumberFormatException, to answer this. We would have to understand how multi-catch works. Since NumberFormatException extends IllegalArgumentException , it cannot be catch at the same level of hierarchy i.e all the subtypes of particular exception is taken care of if you specify the exception. It is implied that Exception cannot be piped with i.e catch(Exception | ParseException e) will give compilation error.

Each alternative in a multi-catch clause must be able to catch some exception class thrown by the try block and uncaught by previous catch clauses. The second catch (Sub Class of First Catch) clause would cause a compile-time error because exception analysis determines that it is already caught by the first catch clause.

Now if we re-look at the syntax of multicatch exception



catch ( [VariableModifiers] CatchType |  CatchType  VariableDeclaratorId)   
Block


To summarize here are few pointer.

1. A catch clause has exactly one parameter, which is called an exception parameter.
2. An exception parameter may denote its type as either a single class type or a union of two or more class types (called alternatives). The alternatives of a union are syntactically separated by |
3. A catch clause whose exception parameter is denoted as a union of types is called a multi-catch clause.
4. An exception parameter of a multi-catch clause is implicitly declared final if it is not explicitly declared final.
5. Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its argument the thrown exception object.
6. A multi-catch clause can be thought of as a sequence of uni-catch clauses. That is, a catch clause whose exception parameter type is denoted as a union D1|D2|...|Dn is equivalent to a sequence of n catch clauses whose exception parameters have class types D1, D2, ..., Dn, respectively.

For example, the following code:

try {
}
catch (ClassNotFoundException | IllegalAccessException ex) {
    body
}


is semantically equivalent to the following code:

try {
} catch (final ClassNotFoundException ex1) {
    body
} catch (final IllegalAccessException ex2) {
    body 
}


whereby the multi-catch clause with two alternatives has been translated into two separate catch clauses, one for each alternative. A Java compiler is neither required nor recommended to compile a multi-catch clause by duplicating code in this manner, since it is possible to represent the multi-catch clause in a class file without duplication.

This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Suppressed Exceptions Java Example

Suppressed Exceptions Java Example

Also, now with Java 7, exceptions are being suppressed rather than masked. Only one exception can be thrown at a time, meaning that even correct code misses information while handling exceptions. Developers lose significant time debugging when a main exception is masked by a further exception being thrown while closing a resource. Because exception masking is such an important problem in practice, Java SE 7 extends exceptions so that "suppressed" exceptions can be attached to primary exceptions. What we called a "masked" exception previously is actually an exception to be suppressed and attached to a primary exception.

The extensions to java.lang.Throwable are as follows:

1) public final void addSuppressed(Throwable exception) appends a suppressed exception to another one, so as to avoid exception masking.

2) public final Throwable[] getSuppressed() gets the suppressed exceptions that were added to an exception.

Following is the example to demonstrate the suppressed exception in Automatic Resource Management in Java 7 and how is that helpful

public class CustomConnectionImpl implements AutoCloseable {


 @Override
    public void close() throws MyException1{
        System.out.println("Closing new connection()");
        throw new MyException1("close");
    }
    
    public void open() throws MyException1 {
        System.out.println("Opening new connection()");
        throw new MyException1("Exception while opening");
        
    }
    
    public static void main(String[] args) {
        try (CustomConnectionImpl autoClose = new CustomConnectionImpl()) {
            autoClose.open();
            
        } catch (MyException1 e) {
            e.printStackTrace();
        }
    }
}
    
    class MyException1 extends Exception {
        
        public MyException1() {
            super();
        }
        
        public MyException1(String message) {
            super(message);
        }
    }


Generates the below output :



Opening new connection()
Closing new connection()
com.java7.coin.trycatch.MyException1: Exception while opening
 at com.java7.coin.trycatch.CustomConnectionImpl.open(CustomConnectionImpl.java:14)
 at com.java7.coin.trycatch.CustomConnectionImpl.main(CustomConnectionImpl.java:20)
 Suppressed: com.java7.coin.trycatch.MyException1: close
  at com.java7.coin.trycatch.CustomConnectionImpl.close(CustomConnectionImpl.java:9)
  at com.java7.coin.trycatch.CustomConnectionImpl.main(CustomConnectionImpl.java:22)


Following is the example to demonstrate the suppressed exception without using ARM for better debugging of expressions

public class CustomConnectionImpl implements AutoCloseable {
 public static void runWithSupressed () throws MyException1 {
  CustomConnectionImpl autoClose = new CustomConnectionImpl();
  MyException1 myException = null;
  try {
   autoClose.open();
  } catch (MyException1 e) {
   myException = e;
   throw e;
  } finally {
   if (myException != null) {
    try {
     autoClose.close();
    } catch (Throwable t) {
     myException.addSuppressed(t);
    }
   } else {
    autoClose.close();
   }
  }
 }

 @Override
 public void close() throws MyException1{
  System.out.println("Closing new connection()");
  throw new MyException1("close");
 }


 public void open() throws MyException1 {
  System.out.println("Opening new connection()");
  throw new MyException1("Exception while opening");
 }

 public static void main(String[] args) {
  try {
   runWithSupressed();        
  } catch (Throwable t) {
   t.printStackTrace();
  }
 }
}

class MyException1 extends Exception {
 public MyException1() {
  super();
 }

 public MyException1(String message) {
  super(message);
 }
}
}


Generates the below output:

Opening new connection()
Closing new connection()
com.fundamentals.exceptionhandling.MyException1: Exception while opening
at com.fundamentals.exceptionhandling.CustomConnectionImpl.open(CustomConnectionImpl.java:35)
at com.fundamentals.exceptionhandling.CustomConnectionImpl.runWithSupressed(CustomConnectionImpl.java:10)
at com.fundamentals.exceptionhandling.CustomConnectionImpl.main(CustomConnectionImpl.java:42)
Suppressed: com.fundamentals.exceptionhandling.MyException1: close
at com.fundamentals.exceptionhandling.CustomConnectionImpl.close(CustomConnectionImpl.java:30)
at com.fundamentals.exceptionhandling.CustomConnectionImpl.runWithSupressed(CustomConnectionImpl.java:17)
... 1 more


Thus demystifying the syntactic sugar of the ARM says that is much more beyond the expression. Moreover, it helps us to worry about what to do with resources rather than management of it. Using it not only simplifies the code, but also eradicates our nasty and redundant code, making the business logic more readable. Also, with the help of suppressed exception it helps us to debug our application correctly.

This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Custom AutoCloseable Java 7 Example

Custom AutoCloseable Java 7 Example

A new interface called java.lang.AutoCloseable was introduced in Java 7. All the resources like Streams, Connections in java implements this interface. We already saw three resources, Result set, connection , Statement. Dataoutputstream, FileOutputStreram are other examples of implementation of this resources.

Autocloseable interface has a method called close() that may throw checked exception. Such close() methods have been retro-fitted into many classes , including the

1) java.io
2) java.nio
3) javax.crypto
4) java.security
5) java.util.zip
6) java.util.jar
7) javax.net
8) java.sql packages

The AutoClosable interface only has a single method called close(). Here is how the interface looks:

public interface AutoClosable {
    public void close() throws Exception;
}


So, if we have to create a custom autoclose implementation we will have to implement autocloseable interface as shown below :

public class CustomConnectionImpl implements AutoCloseable {

 @Override
    public void close() {
        System.out.println("Closing new connection()");
        
    }
    
    public void open() throws MyException1 {
        System.out.println("Opening new connection()");
        
    }
    
    public static void main(String[] args) {
        try (CustomConnectionImpl autoClose = new CustomConnectionImpl()) {
            autoClose.open();
        } catch (MyException1 e) {
            e.printStackTrace();
        }
    }
}
    
    class MyException1 extends Exception {
        
        public MyException1() {
            super();
        }
        
        public MyException1(String message) {
            super(message);
        }
    }


Running the above main file will generate below output :

Output:
Opening new connection()
Closing new connection()


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Types of try-with-resource statements in Java 7

Types of try-with-resource statements in Java 7

In our last post, we learned the basics of "Automatic Resource Management - try-with-resources Statement"

basic try-with-resources statement : A try-with-resources statement with no catch clauses or finally clause is called a basic try-with-resources statement.

try (VariableModifiers R Identifier = Expression ...)
    Block


extended try-with-resources statement : A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

The meaning of an extended try-with-resources statement:

try (VariableModifiers R Identifier = Expression)
    Block
[Catches]
[Finally]


is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:

try {
    try (VariableModifiers R Identifier = Expression)
        Block
}
[Catches]
[Finally]



The meaning of an extended try-with-resources statement with multiple resources:

try (VariableModifiers R Identifier1 = Expression;
VariableModifiers R Identifier2 = Expression;)
    Block
Catches
Finally


is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:

try {
    try (VariableModifiers R Identifier1 = Expression)
        Block
}
[Catches]
[Finally]

try {
    try (VariableModifiers R Identifier2 = Expression)
        Block
}
[Catches]
[Finally]


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

Automatic Resource Management - try-with-resources Statement

Automatic Resource Management - try-with-resources Statement

Recently I was reviewing some old Java code that performs SQL queries against a database and closes the resources in finally blocks. When I examined the code I realized that the handling of the resources was flawed if an exception occurred and not handled with care.

Automatic Resource Management(ARM) is new feature of Java 7 suggested as the part of "Project Coin" which enables the safe handling of resources. Before Java 7 it was developer's responsibility to handle the resources. Developer had to ensure that they manage their resources well.

Resource management, if not handled properly leads to memory leaks or resource leaks. Yet both experienced and inexperienced developer gets the resource management code wrong. For any resources that was successfully initialized needs to be closed. This needs the correct usage of try/catch/finally blocks. Sometimes even your finally block runs into exception while closing in cases, you will have to handle the exception of finally block too. To avoid these exception, we generally ignore the exception in the finally block.

Let’s analyze the following code snippet:

public static int getRecordCount(){
        int recCount= -1;
        Connection c = null;
        Statement stmt = null;
        ResultSet rs = null;
        String select = "SELECT COUNT(*) FROM RECORD_M WHERE ID = 1";
        String URL = "jdbc:oracle:thin:username/password@hostname:port:dbname";
        try {           
        
            c = DriverManager.getConnection(URL);
            stmt = c.createStatement();
            rs = stmt.executeQuery(select);
            if (rs.next())
                recCount = rs.getInt(1);
        
        } catch (Exception ex) {
            //Log.logError(Log.SERVICE, this,
                    //"SQL Error occured while selecting record");
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException e) {
            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
            }
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                }
            }
        }
        return recCount;
    }


Issues with traditional closing of Resources

1) Scope : We had to create the object before try block and thereby increase the scope of resource objects.

2) Redundant code.

3) Null Check : Null check for all the resources in the finally block.

4) Overwrite Exception of try block : If an exception is thrown in the try block and a subsequent exception is thrown in the finally block the original exception is lost.

5) Resource Leak : If an exception is thrown by the closing of the ResultSet (assuming we are throwing exception after we are catching SQLException), no attempt is made to close the Statement and connection objects, causing resource leak.



6) Exception Masking : It is possible for the statement.close() to be the original exception and this is ignored. Ignoring an exception is likely to mislead a user trying to determine the cause of a failure. This is known as exception masking.

Resources such as Connections, ResultSet, Statement, etc. should be closed manually by the developer by writing bog-standard code i.e. try-finally block to close the respective resources.

Also, since you have to make the resources available for finally block to close. You have increase the scope of resources. If you don’t have to close the resources in the finally block. You could have made the scope of the resources local to keep the memory usage low.

Let’s go through the essentials of the try-with-resources statement from the Java developer point of view and elucidate the mystery of the syntactic sugar behind the language extension.

Let’s assume that finally block doesn’t exist so if we have to write the above excerpt we would have written it as

public static int getRecordCount() throws SQLException{
 int recCount= -1;
 try {           
        String URL = "jdbc:oracle:thin:username/password@hostname:port:dbname";
  Connection c = DriverManager.getConnection(URL);
  String select = "SELECT COUNT(*) FROM RECORD_M WHERE ID = 1";
  Statement stmt = c.createStatement();
  ResultSet  rs = stmt.executeQuery(select);
  if (rs.next()) {
   recCount = rs.getInt(1);        
  }
  rs.close();
  stmt.close();
  c.close();
 } catch (Exception ex) {
 //Log.logError(Log.SERVICE, this SQL Error occured while selecting record");
 } 
 return recCount;
}


At first sight this code doesn’t look harmful. It opens a connection, read the data and return. However we might run in SQLException, which can be due to wrong query or other reasons. This might lead our resources open. Hence this approach results into leakage of resources. Also, since we have instances not closed, they are still using memory and we much end up into heap space issue especially we have huge application and heavy calls to DB.

There is lot boilerplate code to ensure that our resources are closed properly in every instance. Such redundant code makes developer worry about the resources rather than required result & logic.

Applying "try-with-resources" statement

public static int getRecordCount() {
 int recCount = -1;
 String URL = "jdbc:oracle:thin:username/password@hostname:port:dbname";
 String select = "SELECT COUNT(*) FROM RECORD_M WHERE ID = 1";
 try (Connection c = DriverManager.getConnection(URL);
  Statement stmt = c.createStatement();
  ResultSet rs = stmt.executeQuery(select);) {
  if (rs.next()) {
   recCount = rs.getInt(1);
  }
 } catch (Exception ex) {
  // Log.logError(Log.SERVICE, this SQL Error occured while selecting
  // record");
 }
 // Finally block can be added to do other activies
 return recCount;
}


A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically. Catch clauses and a finally clause are often unnecessary when resources are closed automatically.

Following is the Syntax of Try with Resource Block:

TryWithResourcesStatement:
    try (Modifier Type VariableName = Expression; 
[Modifier Type VariableName = Expression])
{
Block
}
[Catches]
[Finally]


Also, following statements holds true in case of try with blocks

1) Multiple Resources for try statement : We can have one or more local variables with initialize expressions to act as resources for the try statement.

2) Resources are final : Resources are implicitly declared as final. It will throw compile time error "Resource X of try-with-resources cannot be assigned".

3) Resource must implement AutoCloseable interface : Resources must be a subtype of AutoCloseable, or a compile-time error occurs "Resource type "X" does not implement java.lang.Autocloseable."

4) Scope of resource variables : Scope of variable declared is within the limit of entire try block associated with the try-with-resources statement and same name cannot be redeclared within the try block as local variable unless shadowed using Local Class.

5) Exception in Resource Initialization : Resources are initialized in left-to-right order. If a resource fails to initialize (that is, its initialize expression throws an exception), then all resources initialized so far by the try-with-resources statement are closed. If all resources initialize successfully, the try block executes as normal and then all non-null resources of the try-with-resources statement are closed.

6) Resource Closing: Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.

This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.