A JDBC ResultSet begins before its first row and advances with next. Primitive getters return a Java primitive even for SQL NULL, so wasNull must be checked immediately after that getter.
Java ResultSet: cursor position and SQL NULL are separate states
Operational contract
A zero from getInt can mean a stored zero or SQL NULL. Calling another getter before wasNull changes which read the flag describes. The method below maps an optional reserved quantity to Integer, preserving zero and absence as distinct values. It uses a forward-only read and closes the result and statement together. The SQL orders rows explicitly; ResultSet traversal order without ORDER BY is not a report contract. A missing row remains different from a row with a null quantity.
Failure case
A dispatch report contains one receipt with zero reserved units and another with no quantity reported. Turning both into zero would hide missing source data. The mapping keeps the second value null for an upstream validation decision. The caller can then reject incomplete quantities without distorting the first receipt's legitimate zero.
Java code
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReservationRows {
public static List<Integer> quantities(Connection connection) throws SQLException {
List<Integer> quantities = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement(
"SELECT reserved_qty FROM receipt_intake ORDER BY receipt_id");
ResultSet rows = statement.executeQuery()) {
while (rows.next()) {
int quantity = rows.getInt(1);
quantities.add(rows.wasNull() ? null : quantity);
}
}
return quantities;
}
}Performance and ownership cost
Reading N rows is O(N) time and the returned list uses O(N) memory. A streaming consumer can reduce retained memory, but driver fetch behavior and connection lifetime still matter. Never infer a complete business population merely because next eventually returns false; filters and snapshot isolation determine which rows were queried.
Common Mistakes
- Do not call a primitive zero proof that the SQL column was non-null.
- Do not invoke wasNull after reading another column.
- Do not read a getter before next positions the cursor on a row.
Connected lessons
- Java JDBC PreparedStatement: values stay outside SQL grammar
- Java JDBC transactions: atomic updates and rollback
- Java Optional: absence without hidden failure
- Java JDBC batches: inspect update counts and own rollback
- Java JDBC generated keys: validate one insert and one returned identity
- Java JDBC fetch size: a hint, not a memory guarantee
- Java file, JDBC, and subprocess boundaries quiz
- Advanced Java
Continue with: Java JDBC ResultSet binary streams: read before advancing the cursor.
