杰瑞科技汇

Java String判空,isEmpty()与null有何区别?

Of course! Checking if a Java String is empty or null is a very common task. Here’s a comprehensive guide covering the best ways to do it, from the most modern to the classic approaches.

Java String判空,isEmpty()与null有何区别?-图1
(图片来源网络,侵删)

The Short Answer (TL;DR)

For modern Java (8+), the most robust and concise way is:

String myString = "some value"; // or null, or ""
if (myString == null || myString.isEmpty()) {
    System.out.println("String is null or empty.");
} else {
    System.out.println("String is not null and not empty.");
}

The Classic isEmpty() Method

The isEmpty() method is the standard way to check if a String has a length of zero.

Key Point: isEmpty() only checks for an empty string (). It will throw a NullPointerException if the String variable is null.

Example:

String emptyString = "";
String nonEmptyString = "Hello";
System.out.println(emptyString.isEmpty());      // Output: true
System.out.println(nonEmptyString.isEmpty());   // Output: false
String nullString = null;
// System.out.println(nullString.isEmpty()); // This will throw a NullPointerException!

When to use: Use isEmpty() when you are certain the String variable is not null.

Java String判空,isEmpty()与null有何区别?-图2
(图片来源网络,侵删)

The Robust null Check + isEmpty()

This is the most common and safe pattern for production code. You first check if the object is null before trying to call any methods on it.

Example:

String myString = "test"; // Try changing this to null or ""
if (myString == null || myString.isEmpty()) {
    System.out.println("String is null or empty.");
} else {
    System.out.println("String contains: '" + myString + "'");
}

Explanation:

  1. myString == null: If this is true, the second part of the (OR) expression is not evaluated due to "short-circuiting". This prevents the NullPointerException.
  2. myString.isEmpty(): This is only evaluated if myString is not null.

When to use: This is the go-to solution for most situations before Java 8. It's clear, safe, and universally understood.


The Modern Java 8+ isBlank() Method (Recommended for Java 8+)

Since Java 11, the String class has a fantastic new method: isBlank().

Java String判空,isEmpty()与null有何区别?-图3
(图片来源网络,侵删)

Key Points:

  • It returns true if the string is null or empty ().
  • It also returns true if the string contains only whitespace characters (spaces, tabs, newlines).
  • It's the most convenient and readable way to check for "blank" input.

Example:

String blankString = "   \t \n";
String emptyString = "";
String nonBlankString = "Hello";
System.out.println(blankString.isBlank());    // Output: true
System.out.println(emptyString.isBlank());     // Output: true
System.out.println(nonBlankString.isBlank()); // Output: false
String nullString = null;
System.out.println(nullString.isBlank()); // Output: true (No Exception!)

When to use: This is the best choice for Java 11+. It perfectly handles null, empty, and whitespace-only strings in a single, readable method call.


Alternative Methods (Less Common)

A. Using length()

You can also check the length of the string. This is functionally identical to isEmpty() but slightly more verbose.

String myString = "";
if (myString == null || myString.length() == 0) {
    System.out.println("String is null or has zero length.");
}

This is generally not preferred over isEmpty() because isEmpty() is more explicit about its intent.

B. Using Apache Commons Lang StringUtils

If you're using the Apache Commons Lang library in your project, it provides a very convenient StringUtils.isBlank() method.

First, add the dependency to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Then, you can use it:

import org.apache.commons.lang3.StringUtils;
String myString = "   ";
// This is null-safe and checks for whitespace.
if (StringUtils.isBlank(myString)) {
    System.out.println("String is blank (null, empty, or whitespace).");
}
// It also has isEmpty() which is null-safe.
if (StringUtils.isEmpty(myString)) {
    System.out.println("String is null or empty.");
}

When to use: When you are already using the Apache Commons library in your project and want consistent utility functions.


Summary Table

Method Checks for null? Checks for ? Checks for Whitespace? Best For...
s.isEmpty() ❌ No ✅ Yes ❌ No When you know s is not null.
s == null || s.isEmpty() ✅ Yes ✅ Yes ❌ No General purpose, robust checks in Java < 8.
s.isBlank() (Java 11+) ✅ Yes ✅ Yes ✅ Yes The best choice for Java 11+.
s.length() == 0 ❌ No ✅ Yes ❌ No A more verbose alternative to isEmpty().
StringUtils.isBlank() ✅ Yes ✅ Yes ✅ Yes Projects already using Apache Commons Lang.

Final Recommendation

  • If you are using Java 11 or newer: Always prefer String.isBlank(). It's the most concise, readable, and robust solution.
  • If you are using Java 8, 9, or 10: Use the classic if (myString == null || myString.isEmpty()) pattern. It's the safest and most widely understood approach.
  • If you are working on a large project that already uses Apache Commons: Feel free to use StringUtils.isBlank() for consistency.
分享:
扫描分享到社交APP
上一篇
下一篇