Java – isBlank() vs isEmpty() method of String class


In this short article, you will get to know about the difference between the isBlank() and isEmpty() methods of the String class in Java.

isBlank()isEmpty()
Added in the JDK 11 release.Added in the JDK 1.6 release.
Returns true if a string is empty or only contains white space otherwise returns false.Returns true if the length of the string is 0, otherwise returns false.
It uses Character.isWhitespace(int) method to determine a white space character.It uses the length() method to determine the emptiness of a string.

Checkout the Java 11- New Methods of String Class

Let’s have a look at the below examples.

#test case 1

final String str1 = "";

System.out.println(str1.isBlank()); // return --> true
System.out.println(str1.isEmpty()); // return --> true

#test case 2

final String str2 = "  ";

System.out.println(str2.isBlank()); // return --> true
System.out.println(str2.isEmpty()); // return --> false

#test case 3

final String str3 = "\u2005";

System.out.println(str3.isBlank()); // return --> true
System.out.println(str3.isEmpty()); // return --> false

#test case 4

final String str4 = "  ";

System.out.println(str4.isBlank()); // return --> true
System.out.println(str4.trim().isEmpty()); // return --> true

#test case 5

final String str5 = "\u2005";

System.out.println(str5.isBlank()); // return --> true
System.out.println(str5.trim().isEmpty()); // return --> false

Note: trim() is not aware of Unicode whitespace characters and hence does not consider ‘\u2005′ a whitespace character.

References

  1. Java 11- New Methods of String Class
  2. isBlank() – Java
  3. isEmpty() – Java
  4. Character.isWhitespace(int) – Java

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.