1Z0-809 practice question 17 of 25

Given the structure of the STUDENT table: Student (id INTEGER, name VARCHAR) Given: public class Test { static Connection newConnection =null; public…

Full set: 196 questions
Given the structure of the STUDENT table: Student (id INTEGER, name VARCHAR) Given: public class Test { static Connection newConnection =null; public static Connection get DBConnection () throws SQLException { try (Connection con = DriveManager.getConnection(URL, username, password)) { newConnection = con; } return newConnection; } public static void main (String [] args) throws SQLException { get DBConnection (); Statement st = newConnection.createStatement(); st.executeUpdate(“INSERT INTO student VALUES (102, ‘Kelvin’)”); } } Assume that: The required database driver is configured in the classpath. The appropriate database is accessible with the URL, userName, and passWord exists. The SQL query is valid. What is the result?
Answer options
A: The program executes successfully and the STUDENT table is updated with one record.
B: The program executes successfully and the STUDENT table is NOT updated with any record.
C: A SQLException is thrown as runtime. Correct answer
D: A NullPointerException is thrown as runtime.
Correct Answer:
C. A SQLException is thrown as runtime.
Explanation

The getDBConnection method uses a try-with-resources statement. The Connection object con is created within the scope of this statement. When the try block completes, the connection is automatically closed because Connection implements AutoCloseable. The method then returns newConnection, which is a reference to this now-closed connection. In the main method, calling newConnection.createStatement() on a closed connection object will throw a SQLException, as operations are not permitted on a closed connection.

Why Incorrect

A. The program does not execute successfully because createStatement() is called on a closed connection, which is an invalid operation.
B. The program terminates with an exception before any update can be committed, and it would not execute successfully.
D. A NullPointerException is not thrown because newConnection holds a reference to a closed Connection object; it is not null.

References

1. Oracle Corporation. (2017). The try-with-resources Statement. The Java™ Tutorials. Retrieved from https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html. (This document explains that resources declared in a try-with-resources statement are closed when the statement is finished).

2. Oracle Corporation. (2021). Interface Connection. Java® SE 17 Platform API Specification. Retrieved from https://docs.oracle.com/en/java/javase/17/docs/api/java.sql/java/sql/Connection.html#createStatement(). (The documentation for createStatement() specifies it throws an SQLException "if a database access error occurs or this method is called on a closed connection").

Scroll to Top