// 判断字符串不为空和不为null的示例代码
public class StringCheck {
public static void main(String[] args) {
String str1 = null;
String str2 = "";
String str3 = "Hello, World!";
// 检查字符串是否为null或空
System.out.println("str1 is " + (isNullorEmpty(str1) ? "invalid" : "valid"));
System.out.println("str2 is " + (isNullorEmpty(str2) ? "invalid" : "valid"));
System.out.println("str3 is " + (isNullorEmpty(str3) ? "invalid" : "valid"));
}
// 定义一个方法来检查字符串是否为null或空
public static boolean isNullorEmpty(String str) {
return str == null || str.isEmpty();
}
}
str1
为 null
,str2
为空字符串 ""
,str3
为 "Hello, World!"
。isNullorEmpty
:该方法接收一个字符串参数,并返回一个布尔值。如果字符串为 null
或者是空字符串(长度为0),则返回 true
,否则返回 false
。main
方法中调用 isNullorEmpty
方法:分别对 str1
、str2
和 str3
进行判断,并输出结果。通过这段代码,可以有效地判断字符串是否为 null
或空字符串。
下一篇:java中switch用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站