This rule raises an issue when a ternary expression is used to perform a null-safe equality check between two objects.

In Java, this specifically refers to patterns like a != null ? a.equals(b) : b == null that can be replaced with Objects.equals().

Why is this an issue?

Manually checking for null before calling equals() is a common pattern, but it’s verbose and error-prone. Developers must remember to handle all null combinations correctly, which increases the chance of mistakes.

Java provides Objects.equals() as a standard utility method that handles all null cases correctly. Using this method:

The Objects.equals() method is available since Java 7 and is the recommended way to perform null-safe equality comparisons.

What is the potential impact?

Using manual null checks instead of Objects.equals() has several impacts:

While this doesn’t directly cause bugs in correctly written code, it increases cognitive load and the risk of introducing errors during maintenance.

How to fix it

Replace the ternary null-check pattern with Objects.equals(). This handles all null cases correctly in a single method call.

The ternary pattern a != null ? a.equals(b) : b == null returns:

This is exactly the behavior of Objects.equals(a, b).

Code examples

Noncompliant code example

if (a != null ? a.equals(b) : b == null) { // Noncompliant
    // ...
}

Compliant solution

if (Objects.equals(a, b)) {
    // ...
}

Resources

Documentation