devxlogo

Simplifying Null Check in Java

Flipped null check in Java using literal.equals

A tiny refactor that has survived every Java version from 8 to 25: flip the null check. To guard against a NullPointerException when comparing a string to a literal, most developers write:

if (object != null && !object.equals("")) {
    // do something
}

You can collapse that to one expression by putting the literal on the left side of equals:

if (!"".equals(object)) {
    // do something
}

Because String.equals returns false when its argument is null, the literal form is null-safe for free. No explicit null check needed.

Modern alternatives

If you control the whole codebase, consider pairing this with Objects.equals(a, b) for two possibly-null values, or Optional.ofNullable(object).filter(s -> !s.isEmpty()) when you want a fluent chain. In 2026 code, StringUtils.isNotEmpty (Apache Commons) and Strings.isNullOrEmpty (Guava) are still common, but the flipped-literal idiom stays useful precisely because it needs zero dependencies.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.