简体   繁体   中英

Any scenario in which String.isEmpty() returns true and String.isBlank() returns false for the same input?

Isn't String.isBlank() equivalent to String.isEmpty() + *whitespace only check* ? While looking at the source code for String.isBlank() , it would return true when the length is zero. But I would like to know if there are any scenarios in which isEmpty() would return a true and isBlank() returns a false for the same input.

The docs say for isEmpty() :

Returns true if, and only if, length() is 0.

The docs of isBlank() :

Returns true if the string is empty or contains only white space codepoints, otherwise false.

Emphasis mine.

So isBlank() seems to cover also all cases of isEmpty() .

There exists only one string where isEmpty() returns true , and that is an empty string "" . isBlank() returns true if an empty string is provided as parameter.

So: no . No case exists where isEmpty() returns true and isBlank() returns false.

And if it does, it is a software bug, provided that the documentation describes the intended behaviour. Or else you have to ask Schrödinger.

There is at least one input for which isEmpty() and isBlank() produce opposite results, and that's a space:

public class MyClass {
    public static void main(String args[]) {
      String s = " ";
      System.out.println("isBlank: "+s.isBlank());
      System.out.println("isEmpty: "+s.isEmpty());
    }
}

Output:

isBlank: true

isEmpty: false

The opposite case where isBlank() returns false and isEmpty returns true does not happen, because as per the documentation , isBlank() returns true only if the string is empty or contains only white space codepoints, and isEmpty() returns true if, and only if, length() is 0. And there is no case of a string of length 0 that is not considered blank.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM