public static void main(String[] args) {
String s="";
System.out.println(s.isEmpty());
System.out.println(s.isBlank());
System.out.println(s.length());
System.out.println(StringUtils.isEmpty(s));
}
- 上面3个都可以判断字符串的长度是否为0,但
" "
和""
的区别是前者是有长度的
public static void main(String[] args) {
String s=" ";
System.out.println(s.isEmpty());
System.out.println(s.isBlank());
System.out.println(s.length());
System.out.println(StringUtils.isEmpty(s));
}
-
因为空格是占一个字符长度的所以只能用isBlank()来判断,或者可以用String类的trim()来把两边的空格去掉再判断;
- StringUtils的isEmpty()可以同时判断String是否为null和String的length是否为0,但不能直接这样写
StringUtils.isEmpty(param.trim())
,这样写如果参数为null的话,还是会报空指针异常的;
- StringUtils的isEmpty()可以同时判断String是否为null和String的length是否为0,但不能直接这样写
所以我觉得判断字符串是否为空的写法比较简单直接(str!=null || !str.isBlank())
,无论哪一种写法在调用函数之前都要先判断是否为null,不然会报错.