final Device d;
[i] try(d = new Device()){
[/i] d.open();
d.read();
d.writeHeader("TEST");
d.close();
}catch(IOException e){
System.out.println("Got Exception");
}
java: the try-with-resources resource must either be a variable declaration or an expression denoting a reference to a final or effectively final variable
Is it a variable declaration? Obviously, no.
Is it an expression denoting a reference to a final or effectively final variable? No, it is an expression denoting a reference to a Device object.
If you like our products and services, please help us by posting your review here.
Yes, I saw that and that is what I addressed. You made d final. But the expression that you have inside try is not d. It is d = new Device(). The value of this expression is a reference to a Device object. The value of this reference is not d although d does point to the same Device object.
If you like our products and services, please help us by posting your review here.
If you are not sure what these statements mean, "But the expression that you have inside try is not d. It is d = new Device().", please go through section 6.1.2 Expressions and Statements of this book. I have attached the relevant pages here.
section_6_1_2_hanumant_deshmukh_1z0-815_fundamentals_1.png (183.77 KiB) Viewed 4075 times
If you like our products and services, please help us by posting your review here.
final Device d;
[i] try(d = new Device()){
[/i] d.open();
d.read();
d.writeHeader("TEST");
d.close();
}catch(IOException e){
System.out.println("Got Exception");
}
java: the try-with-resources resource must either be a variable declaration or an expression denoting a reference to a final or effectively final variable
The issue with the provided code is related to the usage of the try-with-resources statement in Java. The try-with-resources statement is used to automatically manage the closing of resources, such as files, sockets, or other objects that implement the AutoCloseable interface.