java中 如何判断字符串为空

在Java中,可以使用以下方法来判断字符串是否为空:

  1. 使用length()方法判断长度是否为0:
String str = "hello";
if (str.length() == 0) {
    System.out.println("字符串为空");
}
  1. 使用isEmpty()方法判断是否为空字符串:
String str = "hello";
if (str.isEmpty()) {
    System.out.println("字符串为空");
}
  1. 使用trim()方法去除字符串前后的空格,然后再判断是否为空:
String str = "   ";
if (str.trim().isEmpty()) {
    System.out.println("字符串为空");
}

以上方法可以用于判断字符串对象是否为空。请注意,如果字符串对象是null,以上方法都会抛出NullPointerException,所以在使用这些方法前,最好先进行null判断。

String str = null;
if (str == null || str.isEmpty()) {
    System.out.println("字符串为空");
}
 
posted @ 2023-06-27 11:26  CodeWhisperer001  阅读(496)  评论(0编辑  收藏  举报