3

According to this question/answer, this code:

try(PreparedStatement p_stmt = connection.prepareStatement(sql)) {
    p_stmt.setString(1, null);
    ...
}

is equivalent to:

try(PreparedStatement p_stmt = connection.prepareStatement(sql)) {
    p_stmt.setNull(1, java.sql.Types.VARCHAR);
    ...
}

My question is, is this the same with int / Integer ?? In other words, what would this code do:

try(PreparedStatement p_stmt = connection.prepareStatement(sql)) {
    Integer i = null;
    p_stmt.setInt(1, i);
    ...
}

setInt() takes in a primitive int which cannot be null, but the unboxed Integer can be null.

Community
  • 1
  • 1
ryvantage
  • 13,064
  • 15
  • 63
  • 112

1 Answers1

9

This line

p_stmt.setInt(1, i);

is compiled to

p_stmt.setInt(1, i.intValue());

Since i is referencing null, you will get a NullPointerException.

This is explained in more detail in the Java Language Specification.

At run time, unboxing conversion proceeds as follows:

  • [...]
  • If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()
  • If r is null, unboxing conversion throws a NullPointerException
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724