SoFunction
Updated on 2025-05-12

Several ways to judge null and applicable scenario analysis of Java

In Java, determine whether the object isnullIt is one of the most common operations in programming. The following are several main judgment methods and their applicable scenarios:

1. Use directly == null (most basic)

if (obj == null) {
    // Processing logic for null}
  • advantage: Simple and direct, with the best performance (no additional method calls).
  • shortcoming: Each object needs to be processed manually, and the code is redundant.
  • Applicable scenarios: Any scenario, especially performance-sensitive code.

2. () (JDK 8+)

import ;
if ((obj)) {
    // Processing logic for null}
  • advantage: Semantics are clear, Null is safe (passed in null will not NPE).
  • shortcoming: The essence is right== nullThe performance of the packaging is slightly lower than that of direct judgment.
  • Applicable scenarios: The code readability requirements are high, avoiding the risk of null pointers.

3. () (JDK 8+)

if ((obj)) {
    // Processing logic for the object not null}
  • advantage:and()Pairing, semantics are clear.
  • Applicable scenarios: Used in combination with Stream, Optional, etc.

4. Optional class (JDK 8+)

import ;
Optional<String> optional = (obj);
if (()) {
    // Processing logic for the object not null} else {
    // Processing logic for null}
// More elegant usage (avoid if-else)(value -> (value));
  • advantage: Force developers to handle null situations to avoid NPE; support chain operations.
  • shortcoming: The code is a bit cumbersome and is suitable for complex process processing.
  • Applicable scenarios: Handle functional programming that may be missing values, avoiding deep nested null checks.

5. Apache Commons Lang (third-party library)

import .;
if ((obj)) {
    // The object is null or empty (suitable for strings, collections, etc.)}
if ((obj)) {
    // The object is not null and not empty}
  • advantage: Provides richer null value judgments (such as empty strings, empty sets).
  • shortcoming: Dependencies need to be introduced.
  • Applicable scenarios: It is necessary to handle scenarios with multiple types of null values ​​uniformly.

6. StringUtils (Apache Commons Lang)

Specially used for null value judgment of strings:

import .;
if ((str)) {
    // The string is null, empty string or only spaces}
if ((str)) {
    // The string is null or empty string (no space check)}
  • advantage: More comprehensive when processing strings to avoid() == 0NPE risks.
  • Applicable scenarios: String processing scenario.

7. Triple operator (simplified assignment)

// Assign default values ​​when the object is nullString result = (obj == null) ? "default" : obj;
// Equivalent toString result;
if (obj == null) {
    result = "default";
} else {
    result = obj;
}
  • advantage: The code is concise and suitable for simple assignment scenarios.
  • shortcoming: Readability decreases when logic is complex.

8. Use assertions (development stage)

import static ;
// Mandatory object non-empty during testing or developmentassertNotNull(obj, "Object cannot be null");
  • advantage: Quickly locate problems to avoid incorrect data flowing into subsequent processes.
  • shortcoming: Assertion is disabled in production environment by default and cannot be used for business logic judgment.
  • Applicable scenarios: Unit testing, method parameter verification.

Performance comparison

Way Performance (relative)
== null Fastest
() near==
Optional Slower (involving object creation)

Best Practices

  • Priority use== null: Direct judgment of simple scenarios, optimal performance.
  • For complex processesOptional: Avoid deep nested null checks to improve code readability.
  • For string processingStringUtils:avoid()NPE risks.
  • For collections/arrays(): Unified processing of various types of null values.
  • Avoid overuseOptional: The direct judgment of simple scenarios is clearer, and abuse will lead to code redundancy.

Example comparison

Traditional way

if (user != null && () != null && ().getCity() != null) {
    (().getCity());
}

Optional method

(user)
        .map(User::getAddress)
        .map(Address::getCity)
        .ifPresent(::println);

Choosing the appropriate judgment method based on the scene can not only ensure the robustness of the code, but also improve readability.

This is the end of this article about several ways to judge null by Java. For more related content on null by Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!