Does java have an equivalent to the C# "using" clause

java, syntax

Solution

Yes. Java 1.7 introduced the try-with-resources construct allowing you to write:

try(InputStream is1 = new FileInputStream("/tmp/foo");
    InputStream is2 =  new FileInputStream("/tmp/bar")) {
         /* do stuff with is1 and is2 */
}

... just like a `using` statement.

Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:

InputStream is1 = new FileInputStream("/tmp/foo");
try{

    InputStream is2 =  new FileInputStream("/tmp/bar");
    try{
         /* do stuff with is1 and is 2 */

    } finally {
        is2.close();
    }
} finally {
    is1.close();
}

Problem

I've seen reference in some C# posted questions to a "using" clause. Does java have the equivalent?

Original source