1

I am new to Java. I am reading the book Java Programming Interviews Exposed. They have this code on page 255, which I find confusing:

@Test
public void plainJdbcExample() {

  Connection connection = null;

  PreparedStatement insert = null; 

  PreparedStatement query = null; 

  ResultSet resultSet = null; 

  // more code here
}

I guess I don't know much about Java, but I am surprised by this. I thought if a variable had a type such as "Connection" or "PreparedStatement" or "ResultSet" then only values of that type could be assigned to that variable, but here I see "null" being assigned to all of those different variables.

The link above, that the moderator posted, says that null is the default value of any reference type. If so, why would you ever write code like this, where the null value is being explicitly assigned?

charlottesville
  • 467
  • 5
  • 19
  • Where is your question – JamesB Apr 06 '15 at 21:47
  • The penultimate sentence: "Apparently it can be assigned to any variable, no matter the nominal type of the variable?" – charlottesville Apr 06 '15 at 22:10
  • Those are local variables, they are no initialized automatically, so the need to be initialized to _something_. Try to remove those assignments and compile the code. –  Apr 06 '15 at 22:13

0 Answers0