toString() or clone() Returns Null

ID

java.tostring_clone_returns_null

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

clone, reliability

Description

Reports a toString() or clone() method that explicitly returns null instead of a real result.

Rationale

toString() is expected to hand back a string — possibly empty, never absent — and clone() is expected to hand back a copy of the receiver. Returning null from either breaks that expectation and pushes the failure onto the caller: string concatenation, logging, and debuggers all call toString() implicitly and will throw NullPointerException the moment they try to use the result.

// Bad -- caller gets a NullPointerException instead of a string
@Override
public String toString() {
    if (items.isEmpty()) {
        return null;
    }
    return String.join(", ", items);
}

Remediation

Return an empty string from toString(), or a genuine copy from clone() — never null.

// Good -- always returns a usable string
@Override
public String toString() {
    if (items.isEmpty()) {
        return "";
    }
    return String.join(", ", items);
}

© 2026 Xygeni. All rights reserved