try-with-resources
- Java course
- Beginner
- Lesson 98/116
- 5 min
Learn resource management with try-with-resources.
try-with-resources closes resources automatically
try-with-resources declares the resource in parentheses; when the block ends, close() is called automatically. This removes the risk of forgetting to close.
try (Scanner input = new Scanner(System.in)) {
String name = input.nextLine();
System.out.println(name);
}The variable in parentheses must be AutoCloseable; Scanner and BufferedReader comply. Whether or not an exception occurs, closing is guaranteed. This structure has been the recommended way to manage resources since Java 7.
The AutoCloseable interface
For a resource to be used inside try-with-resources, it must implement the AutoCloseable interface. This interface contains a single close() method.
try (BufferedReader r = new BufferedReader(
new InputStreamReader(System.in))) {
System.out.println(r.readLine());
}You can also write nested wrapped resources separated by commas in one pair of parentheses; the closing order runs from outermost to innermost. The Java compiler manages the closing order for you.
Practice Read with try-with-resources
Create a Scanner inside try-with-resources, read a line and print it. The user will type Merhaba. Rely on automatic closing of the resource.
Starter code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner with try-with-resources, read a line, print it
}
}Sample solution
try (Scanner input = new Scanner(System.in)) {
String line = input.nextLine();
System.out.println(line);
}Expected output
Merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Declare the resource inside try
try (____ input = new Scanner(System.in)) {
String name = input.nextLine();
}
try (Scanner input = new Scanner(System.in)) {
String name = input.nextLine();
}
Explanation: the resource type is Scanner and it is declared in parentheses.
2 Complete each sentence
| Term | Meaning |
|---|---|
try-with-resources |
auto close |
AutoCloseable |
closeable interface |
Scanner |
reader |
BufferedReader |
buffered reader |
3 What happens when the try-with-resources block ends?
- The resource stays open
- The program stops
- close() is called automatically Correct answer
- Nothing
Explanation: when the try-with-resources block ends, the resource's close() method is called automatically.