try with resource helps to close open resources that uses .close() method to close.

Transcribed from the original LinkedIn image post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
Try with resource is basically closing the resources where a programmer
would have to manually close FileWriter and BufferedWriter
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Day04 {
    public static void main(String[] args) throws IOException {
        File file = new File("/home/mohibulhasan/Documents/example.txt");

        // try with resource
        try (
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
        ) {
            bufferedWriter.write("Found about try with resource.");
            bufferedWriter.newLine();
        }
    }
}

The original LinkedIn graphic is preserved below.

Day 4 LinkedIn post