Java OCA OCP Practice Question 2039

Question

Which resources have their close() method called when this code runs?.

public static void runQuery(Connection conn) throws SQLException{ 
   try (Statement stmt = conn.createStatement()) { 
      ResultSet rs = stmt.executeQuery("select * from myTable"); 
      rs.next(); 
   } 
} 
  • A. No close() methods are called.
  • B. Only Statement
  • C. Only Statement and Connection
  • D. Only Statement and ResultSet


D.

Note

Since this code opens Statement using a try-with-resources, Statement gets closed automatically at the end of the block.

Further, closing a Statement automatically closes a ResultSet created by it, making Option D the answer.

Remember that you should close any resources you open in code you write.




PreviousNext

Related