Checking for a null int value from a Java ResultSet Checking for a null int value from a Java ResultSet java java

Checking for a null int value from a Java ResultSet


The default for ResultSet.getInt when the field value is NULL is to return 0, which is also the default value for your iVal declaration. In which case your test is completely redundant.

If you actually want to do something different if the field value is NULL, I suggest:

int iVal = 0;ResultSet rs = magicallyAppearingStmt.executeQuery(query);if (rs.next()) {    iVal = rs.getInt("ID_PARENT");    if (rs.wasNull()) {        // handle NULL field value    }}

(Edited as @martin comments below; the OP code as written would not compile because iVal is not initialised)


Another solution:

public class DaoTools {    static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {        int nValue = rs.getInt(strColName);        return rs.wasNull() ? null : nValue;    }}


I think, it is redundant. rs.getObject("ID_PARENT") should return an Integer object or null, if the column value actually was NULL. So it should even be possible to do something like:

if (rs.next()) {  Integer idParent = (Integer) rs.getObject("ID_PARENT");  if (idParent != null) {    iVal = idParent; // works for Java 1.5+  } else {    // handle this case  }      }