Checking NULL Values in JDBC ResultSet
Fast recall
Quick revision
Core answer
Whether you know primitive getters return 0 for NULL and how to detect it.
Treating a returned 0/false as a real value when the column was NULL.
Use wasNull() immediately after the read, or getObject for nullable columns.
Interview-ready guide
Interview answer
int score = rs.getInt("score"); boolean missing = rs.wasNull(); is the classic pattern. If score can be absent, mapping it directly to primitive int loses information; use Integer and getObject where the driver supports the requested conversion. For String name = rs.getString("name"), a SQL NULL becomes Java null, so wasNull is usually unnecessary for that getter.
For example, getInt("discount") returns 0 for both SQL NULL and zero. Calling wasNull() immediately afterward, or using getObject with Integer, preserves the difference.
Checking NULL Values in JDBC ResultSet
Direct Answer
Primitive-style getters such as getInt and getLong return 0 when the SQL value is NULL, so call wasNull immediately after that getter to distinguish NULL from a real zero. getObject can return Java null, and modern JDBC can request a wrapper/type such as getObject(column, Integer.class) when supported. Reference getters such as getString normally return null for SQL NULL.
Common Mistakes & Pitfalls
- Trusting a returned 0/false: it may be a NULL, not a real value.
- Calling
wasNull()too late: it refers to the last column read — call it right after. - Mapping nullable columns to primitives: use wrappers/
getObject. - Forgetting
getStringreturns null: object getters already handle NULL.
Check your understanding
Answer these without looking back at the article.
- What is a ResultSet in JDBC and how do you iterate it?
- How do you map ResultSet rows to Java objects in JDBC?
- What happens if you do not close a ResultSet in JDBC?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.