Skip to content

Latest commit

 

History

History
89 lines (64 loc) · 2.8 KB

File metadata and controls

89 lines (64 loc) · 2.8 KB

Java 程序:检查字符串是否为空或null

原文: https://www.programiz.com/java-programming/examples/string-empty-null

在此程序中,您将学习使用if-else语句和 Java 函数检查字符串是否为空或null

示例 1:检查字符串是否为空或null

public class Null {

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

        if(isNullOrEmpty(str1))
            System.out.println("First string is null or empty.");
        else
            System.out.println("First string is not null or empty.");

        if(isNullOrEmpty(str2))
            System.out.println("Second string is null or empty.");
        else
            System.out.println("Second string is not null or empty.");
    }

    public static boolean isNullOrEmpty(String str) {
        if(str != null && !str.isEmpty())
            return false;
        return true;
    }
}

运行该程序时,输出为:

str1 is null or empty.
str2 is null or empty.

在上面的程序中,我们有两个字符串str1str2str1包含空值,str2是空字符串。

我们还创建了一个函数isNullOrEmpty(),顾名思义,该函数检查字符串是空还是空。 它使用字符串的!= nullisEmpty()方法使用空检查来对其进行检查。

简而言之,如果字符串不是nullisEmpty()返回false,则它既不是null也不为空。 否则,是的。

但是,如果字符串仅包含空格字符(空格),则上述程序不会返回空。 从技术上讲,isEmpty()看到它包含空格并返回false。 对于带空格的字符串,我们使用字符串方法trim()修剪掉所有前导和尾随空格字符。


示例 2:检查带空格的字符串是否为空或null

public class Null {

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

        if(isNullOrEmpty(str1))
            System.out.println("str1 is null or empty.");
        else
            System.out.println("str1 is not null or empty.");

        if(isNullOrEmpty(str2))
            System.out.println("str2 is null or empty.");
        else
            System.out.println("str2 is not null or empty.");
    }

    public static boolean isNullOrEmpty(String str) {
        if(str != null && !str.trim().isEmpty())
            return false;
        return true;
    }
}

运行该程序时,输出为:

str1 is null or empty.
str2 is null or empty.

isNullorEmpty()中,我们添加了一个额外的方法trim(),该方法删除了给定字符串中的所有前导和尾随空白字符。

因此,现在,如果字符串仅包含空格,该函数将返回true