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

要理解此示例,您应了解以下Java编程主题


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

class Main {
  public static void main(String[] args) {
    
    // create null, empty, and regular strings
    String str1 = null;
    String str2 = "";
    String str3 = "  ";

    // check if str1 is null or empty
    System.out.println("str1 is " + isNullEmpty(str1));

    // check if str2 is null or empty
    System.out.println("str2 is " + isNullEmpty(str2));

    // check if str3 is null or empty
    System.out.println("str3 is " + isNullEmpty(str3));
  }

  // method check if string is null or empty
  public static String isNullEmpty(String str) {

    // check if string is null
    if (str == null) {
      return "NULL";
    }

    // check if string is empty
    else if(str.isEmpty()){
      return "EMPTY";
    }

    else {
      return "neither NULL nor EMPTY";
    }
  }
}

输出

str1 is NULL
str2 is EMPTY
str3 is neither NULL nor EMPTY

在上面的程序中,我们创建了

  • 一个null字符串 str1
  • 一个空字符串 str2
  • 一个包含空格的字符串 str3
  • isNullEmpty()方法用于检查字符串是否为null或空

这里,str3只包含空格。但是,程序不将其视为空字符串。

这是因为空格在Java中被视为字符,而包含空格的字符串是一个常规字符串。

现在,如果我们希望程序将包含空格的字符串视为空字符串,我们可以使用trim()方法。该方法会删除字符串中存在的所有空格。


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

class Main {
  public static void main(String[] args) {
    
    // create a string with white spaces
    String str = "    ";

    // check if str1 is null or empty
    System.out.println("str is " + isNullEmpty(str));
  }

  // method check if string is null or empty
  public static String isNullEmpty(String str) {

    // check if string is null
    if (str == null) {
      return "NULL";
    }

    // check if string is empty
    else if (str.trim().isEmpty()){
      return "EMPTY";
    }

    else {
      return "neither NULL nor EMPTY";
    }
  }
}

输出

str is EMPTY

在上面的示例中,注意检查空字符串的条件

else if (str.trim().isEmpty())

在这里,我们在isEmpty()之前使用了trim()方法。这将

  1. 删除字符串中存在的所有空格
  2. 检查字符串是否为空

因此,我们得到输出 str is EMPTY

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战