使用javaisempty()方法判断字符串是否为空教程
来源:好程序员 发布人:yyy

在Java中,我们可以使用isEmpty()方法检查一个字符串是否为空。isEmpty()方法是一个String类的实例方法,用于检查一个字符串是否为空。
下面是使用isEmpty()方法的示例代码:
String str1 = "hello";
String str2 = "";
// 检查字符串是否为空
if (str1.isEmpty()) {
System.out.println("str1 is empty");
} else {
System.out.println("str1 is not empty");
}
if (str2.isEmpty()) {
System.out.println("str2 is empty");
} else {
System.out.println("str2 is not empty");
}
在这个示例中,我们定义了两个字符串,str1和str2。我们使用isEmpty()方法检查这两个字符串是否为空。
输出结果为:
str1 is not empty
str2 is empty
isEmpty()方法返回一个布尔值,如果调用该方法的字符串长度为0,则返回true。否则,返回false。
需要注意的是,isEmpty()方法只能检查字符串是否为空,而不能检查字符串是否为null。如果想检查字符串是否为null,需要使用==运算符或Objects.isNull()方法。
下面是一个检查字符串是否为null的示例代码:
String str = null;
// 检查字符串是否为null
if (str == null) {
System.out.println("str is null");
} else if (str.isEmpty()) {
System.out.println("str is empty");
} else {
System.out.println("str is not empty");
}
在这个示例中,我们先检查字符串是否为null,如果为null,则输出str is null;否则,使用isEmpty()方法检查字符串是否为空。