Faulty null checks can lead to NullPointerException at runtime, which crashes the application unexpectedly.
The most common mistake is using the wrong logical operator when combining a null check with property or method access on the same variable:
- Using OR (
||) instead of AND (&&) when checking that an object is not null before accessing it
- Using AND (
&&) instead of OR (||) when checking that an object is null
For example, if (name != null || name.length > 0) is problematic because:
- If
name is not null, the first condition name != null is true
- Due to short-circuit evaluation,
name.length > 0 won’t be evaluated, which might not be the intended behavior
- If
name is null, the first condition is false, so the second condition name.length > 0 will be evaluated
- Accessing
length on a null object throws a NullPointerException
Similarly, if (record == null && record.id > 10) is wrong because if record is null, the first condition is
true, but then record.id > 10 will still be evaluated, causing a NullPointerException.
These logical errors are often typos or misunderstandings of how logical operators work with short-circuit evaluation.
What is the potential impact?
The application will crash with a NullPointerException when the faulty null check is executed and the object being checked is actually
null. This can lead to:
- Application downtime and poor user experience
- Data loss if the exception occurs during critical operations
- Security vulnerabilities if error handling is inadequate
- Difficult debugging, especially in production environments where the exact conditions causing the null reference may be hard to reproduce