Few new methods have been introduced in Java 11, String class. One of them is isBlank() method.
isBlank() method returns true if the string is empty or contains white space characters only. If the string contains multiple white space characters and no other characters then also true is returned.
Let us look at an example code :
public class Tech4Humans {
public static void main(String[] args) {
// Empty String
String str1 = "";
System.out.println(str1.isBlank()); //true
// Single White space character
String str2 = "\n";
System.out.println(str2.isBlank()); //true
// multiple White space characters
String str3 = "\n\t";
System.out.println(str3.isBlank()); //true
String str5 = " ";
System.out.println(str5.isBlank()); //true
String str6 = " \n";
System.out.println(str6.isBlank()); //true
String str7 = "Tech4Humans";
System.out.println(str7.isBlank()); //false
}
}
Output
true
true
true
true
true
false
isEmpty() is another method in String class. By naming isEmpty and isBlank methods looks similar but there is a slight difference between them. Let us see the difference – isBlank() vs isEmpty().