Given:
public class SampleClass {
public static void main(String[] args) {
SampleClass sc = new SampleClass();
sc.processCD();
}
private void processCD() {
try (CDStream cd = new CDStream()) {
cd.open();
cd.read();
cd.write("lullaby");
cd.close();
} catch (Exception e) {
System.out.println("Exception thrown");
}
class CDStream {
String cdContents = null;
public void open() {
cdContents = "CD Contents";
System.out.println("Opened CD stream");
}
public String read() throws Exception {
throw new Exception("read error");
}
public void write(String str) {
System.out.println("CD str is: " + str);
}
public void close() {
cdContents = null;
}
What is the result?
A.
Compilation CD stream
B.
Opened CD thrown
C.
Exception thrown
D.
Opened CD stream
CD str is: lullaby
Explanation:
In this example the compilation of line ” try (CDStream cd = new CDStream()) {” will
fail, as
try-with-resources not applicable to variable type CDStream.
Note: The try-with-resources statement is a try statement that declares one or more resources. A
resource is an object that must be closed after the program is finished with it. The try-withresources statement ensures that each resource is closed at the end of the statement. Any object
that implements java.lang.AutoCloseable, which includes all objects which implement
java.io.Closeable, can be used as a resource.
Reference: The Java Tutorials,The try-with-resources Statement
The anwser is wrong, CDStream must implements java.lang.AutoCloseable interface, if not, compilations fails
“The resource type CDStream does not implement java.lang.AutoCloseable”