Java 判断字符串是否为空或者 null

在 Java 里,判断字符串是否为空或者 null 是很常见的操作。下面为你介绍几种不同的判断方式。

1. 手动判断

你可以通过 == null 判断字符串是否为 null,用 length() == 0 判断字符串是否为空。示例代码如下:

public class StringCheckExample {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";
        String str3 = "hello";

        System.out.println(isNullOrEmpty(str1)); 
        System.out.println(isNullOrEmpty(str2)); 
        System.out.println(isNullOrEmpty(str3)); 
    }

    public static boolean isNullOrEmpty(String str) {
        return str == null || str.length() == 0;
    }
}

代码解释

  • str == null:用来判断字符串是否为 null
  • str.length() == 0:用来判断字符串是否为空。

2. 使用 isEmpty() 方法

从 Java 6 开始,String 类提供了 isEmpty() 方法,该方法可以判断字符串长度是否为 0。示例代码如下:

public class StringCheckExample {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";
        String str3 = "hello";

        System.out.println(isNullOrEmpty(str1)); 
        System.out.println(isNullOrEmpty(str2)); 
        System.out.println(isNullOrEmpty(str3)); 
    }

    public static boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }
}

代码解释

  • str == null:判断字符串是否为 null
  • str.isEmpty():判断字符串长度是否为 0。

3. 使用 Apache Commons Lang 库

Apache Commons Lang 库提供了 StringUtils 类,其中的 isBlank() 和 isEmpty() 方法可以方便地判断字符串是否为空或者 null。要使用这个库,你需要在项目中添加依赖。以 Maven 为例,在 pom.xml 中添加以下依赖:

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

示例代码如下:

import org.apache.commons.lang3.StringUtils;

public class StringCheckExample {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";
        String str3 = "hello";

        System.out.println(StringUtils.isBlank(str1)); 
        System.out.println(StringUtils.isBlank(str2)); 
        System.out.println(StringUtils.isBlank(str3)); 
    }
}

代码解释

  • StringUtils.isBlank():可以判断字符串是否为 null、空字符串或者只包含空白字符。
  • StringUtils.isEmpty():只判断字符串是否为 null 或者空字符串。

4. 使用 Java 11 的 isBlank() 方法

从 Java 11 开始,String 类提供了 isBlank() 方法,该方法可以判断字符串是否为 null、空字符串或者只包含空白字符。示例代码如下:

public class StringCheckExample {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";
        String str3 = "hello";

        System.out.println(isNullOrBlank(str1)); 
        System.out.println(isNullOrBlank(str2)); 
        System.out.println(isNullOrBlank(str3)); 
    }

    public static boolean isNullOrBlank(String str) {
        return str == null || str.isBlank();
    }
}

代码解释

  • str == null:判断字符串是否为 null
  • str.isBlank():判断字符串是否为空或者只包含空白字符。

猜你喜欢

转载自blog.csdn.net/a876106354/article/details/147133483
今日推荐