Page 1 of 1
About Question enthuware.ocpjp.v17.2.1208 :
Posted: Wed Mar 06, 2024 10:43 pm
by likejudo
I am trying to understand why this fails to compile
Code: Select all
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
Re: About Question enthuware.ocpjp.v17.2.1208 :
Posted: Wed Mar 06, 2024 11:16 pm
by admin
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.
Re: About Question enthuware.ocpjp.v17.2.1208 :
Posted: Thu Mar 07, 2024 8:14 am
by likejudo
admin wrote: ↑Wed Mar 06, 2024 11:16 pm
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.
But even when I made it final (please see snippet above) it would not compile.
Re: About Question enthuware.ocpjp.v17.2.1208 :
Posted: Thu Mar 07, 2024 8:54 am
by admin
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.
Re: About Question enthuware.ocpjp.v17.2.1208 :
Posted: Thu Mar 07, 2024 9:05 am
by admin
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 4037 times
Re: About Question enthuware.ocpjp.v17.2.1208 :
Posted: Thu Mar 07, 2024 10:36 am
by likejudo
thank you
Re: About Question enthuware.ocpjp.v17.2.1208 :
Posted: Sun Mar 24, 2024 9:38 pm
by lowlysute
likejudo wrote: ↑Wed Mar 06, 2024 10:43 pm
I am trying to understand why this fails to compile
drift hunters
Code: Select all
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.