Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 15
Question ID: UKOCP83800
Given structure of EMPLOYEE table:
EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100), SALARY real, PRIMARY KEY (ID))
EMPLOYEE table contains below records:
- 101 John Smith 12000
- 102 Sean Smith 15000
- 103 Regina Williams 15500
- 104 Natasha George 14600
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.sql.*;
- public class Test {
- public static void main(String[] args) throws SQLException {
- var url = "jdbc:mysql://localhost:3306/ocp";
- var user = "root";
- var password = "password";
- var query = "Select * from EMPLOYEE";
- Connection con = DriverManager.getConnection(url, user, password);
- try (var stmt = con.createStatement())
- {
- var rs = stmt.executeQuery(query);
- }
- }
- }
Also assume:
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.
Which of the following objects will get closed?
Choose 2 options.
- A Connection object
- B Statement object
- C ResultSet object
- D None of the objects will get closed as close() method is not invoked
Reveal correct answers
Correct answers: B, C
Explanation
UKOCP83800:
Variables 'url', 'user', 'password' and 'query' infer to String type. Variable 'con' infers to Connection type, variable 'stmt' infers to Statement type and variable 'rs' infers to ResultSet type.
Statement object is created inside try-with-resources statement. So, close() method is invoked on Statement object implicitly.
According to the javadoc of close() method, "When a Statement object is closed, its current ResultSet object, if one exists, is also closed". Hence, ResultSet object is also closed.
Connection object is created outside of try-with-resources statement, hence close() method of Connection object is not invoked implicitly.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
