Java SE 8 Programmer II — Question 22
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.
- D. A NullPointerException is thrown as runtime.
Correct answer: C
Explanation
The correct answer is C because the variable 'newConnection' is initialized as null and remains null after the method call, leading to a NullPointerException when attempting to create a Statement. Options A and B are incorrect as they imply successful execution and updates, which cannot occur without a valid connection. Option D is wrong because a SQLException, not a NullPointerException, would be thrown due to the null connection.