Page 1 of 1

About Question enthuware.ocpjp.v7.2.1210 :

Posted: Wed Aug 23, 2017 6:24 am
by horst1a
Hello ,
I 've always thought, when using a try-with-resource statement the class has to implement AutoCloseable
but the following code compile without:

package food;
import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;

public class IOTest {
public static void main(String[] args)
{ try(BufferedReader bfr = new BufferedReader(new FileReader("c:\\works\\a.java"))){
String line = null;
while( (line = bfr.readLine()) != null){
System.out.println(line); }
}catch(IOException e){
e.printStackTrace(); } } }

What happens to opened resources if class doesnt implement AutoCloseeable? Will they stay opened ?

Re: About Question enthuware.ocpjp.v7.2.1210 :

Posted: Wed Aug 23, 2017 6:57 am
by admin
horst1a wrote:Hello ,
What happens to opened resources if class doesnt implement AutoCloseeable? Will they stay opened ?
Yes, exactly, you would have to close them explicitly in finally block. That is why try-with-resources/AutoCloseable was introduced in Java 7.

Should go through this tutorial : https://docs.oracle.com/javase/tutorial ... Close.html

HTH,
Paul.

Re: About Question enthuware.ocpjp.v7.2.1210 :

Posted: Wed Aug 23, 2017 7:07 am
by horst1a
Thanx, Paul,

thats what i thought would happen