java怎么判断字符串是否为空

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

使用length()方法,判断字符串的长度是否为0:

String str = "example";
if (str.length() == 0) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}

使用isEmpty()方法,判断字符串是否为空字符串(长度为0):

String str = "example";
if (str.isEmpty()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}

使用isBlank()方法,判断字符串是否为空或只包含空格:

String str = "example";
if (str.isBlank()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}

其中,isBlank()方法是在Java 11中引入的,如果使用的是Java 11或更高版本,建议使用该方法来判断字符串是否为空。

阅读剩余
THE END