Java 的 isEmpty 方法是String 方法之一,用于检查用户指定的字符串是否为空。如果用户指定的字符串长度为零,则 isEmpty 返回 TRUE。
在本文中,我们将通过一个示例展示如何使用 isEmpty 方法查找空字符串。String isEmpty 的基本语法如下所示。
public Boolean isEmpty() // It will return Boolean True or False as Output //In order to use in program String_Object.isEmpty()
- String_Object:请指定有效的 String 对象。
Java String isEmpty 方法示例
isEmpty 方法当且仅当用户指定的字符串长度为零时返回 True。否则,它将返回 False。在这个 Java 程序中,我们将找到相同的内容。
首先,我们声明了三个 String 变量,并为 str 赋值了一些文本。对于另外两个,我们分别赋了一个空字符串和一个空格。
从下面的语句开始,第一个 Java System.out.println 语句将查找上面指定的 str 的长度(为 16)。
第二个语句将调用 isEmpty() 方法来检查上面指定的 str 是否为空。正如我们所知,长度为 16(不等于零),因此 Java String isEmpty 的输出将是 False。
第三个 System.out.println 语句将检查上面指定的 str1 是否为空。正如我们所知,长度为 0,因此输出将是 True。
从下面的屏幕截图中,您可以看到String 函数为 str2 返回 False。这是因为上面指定的 str2 的长度为 1。所以该方法返回 False。
package StringFunctions;
public class StringIsEmpty {
public static void main(String[] args) {
String str = "Tutorial GateWay";
String str1 ="";
String str2 =" ";
System.out.println("The Length of a String Str = " + str.length());
System.out.println("Is this String Str is Empty or Not? = " + str.isEmpty());
System.out.println("\nThe Length of a String Str1 = " + str1.length());
System.out.println("Is this String Str1 is Empty or Not? = " + str1.isEmpty());
System.out.println("\nThe Length of a String Str2 = " + str2.length());
System.out.println("Is this String Str2 is Empty or Not? = " + str2.isEmpty());
}
}
