java

The try-with-resources Statement in Java

The try-with-resources statement is available since Java 7. It allows the declaration of resources which are automatically closed at the end of the try block.
 

Why is closing resources important?

Resources are generally understood to be things like streams, readers, statements, sockets. It is important to always close them cleanly because they mostly represent system resources and can therefore also lock/block them.

In Java these resources implement the interface java.io.Closeable, which in turn extends the interface java.lang.AutoCloseable. It contains the method close(), which is called to release the resource.
 

 

Closing resources in finally block (before Java 7)

A typical use case for finally is reading a file as in the following example:

BufferedReader br = new BufferedReader(new FileReader(path));
try {
    return br.readLine();
} finally {
    // Is still executed after the return!
    if (br != null) { br.close() };
}

The code in the finally block is executed even though the return statement has already been executed. The call of br.close() is passed to the FileReader.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

Closing resources with the try-with-resources statement (Java 7 and higher)

To avoid the not very elegant and partly error-prone finally blocks, the try-with-resources statement is a good choice:

try (BufferedReader br =
               new BufferedReader(new FileReader(path))) {
    return br.readLine();
}

The resources are instantiated in round brackets after the try statement. If several resources are required, they can be separated by commas.

The prerequisite for the try-with-resources statement is that the resource class implements the java.lang.AutoCloseable interface (or java.io.Closeable, as this inherits from AutoCloseable).
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *