

Previously resource to be managed by a try-with-resources statement must be fresh variable declaration in the statement:
try { Resource r =..}
Table of Contents
Java 8 Supported
try (InputStream inputStream = new ByteArrayInputStream("JavaDeveloperZone".getBytes());) { // do some operation } catch (Exception e) { // do some operation } finally { // do some operation }
Java 9 Support
But in Java 9 refined proposal for try-with-resource statement now general expression now allowed variables that are:
- final or
- effectively final
Effectively final variable are not explicitly declared as final, but could be and still have the program compiled.
Example:
InputStream inputStream = new ByteArrayInputStream("JavaDeveloperZone".getBytes()); try (inputStream) { // do some operation } catch (Exception e) { // do some operation } finally { // do some operation }
Why Java 9 require Final or Effectively final?
If compiler allowed to change Object inside that references than compiler will get confuse about which objects close() method will be called to close resource after try execution. here is problematic example which will confuse to compiler.
InputStream inputStream = new ByteArrayInputStream("JavaDeveloperZone".getBytes()); try (inputStream) { inputStream = new ByteArrayInputStream("JavaDeveloperZone".getBytes()); } // Which object(s) should have a close method called?
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.