What is the isBlank() method in Java?

In Java 11, a new method called isBlank() was added in the String class. The isBlank() method will return true in the below cases:

  • If the string is empty.
  • If the string only contains whitespaces.

Example

public class HelloWorld {
public static void main(String[] args) {
String emptyString = "";
System.out.println(emptyString.isBlank()); // true
String emptyStringWithSpace = " ";
System.out.println(emptyStringWithSpace.isBlank()); // true
String emptyStringWithTabSpace = " \n \t ";
System.out.println(emptyStringWithTabSpace.isBlank()); // true
String nonEmptyString = "a";
System.out.println(nonEmptyString.isBlank()); // false
}
}

You can test the above code in an online Java 11 compiler, here.


Before Java 11, we used the trim and the isEmpty() methods to achieve the results of the isBlank() method.

public class HelloWorld {
public static void main(String[] args) {
String emptyString = " ";
boolean isBlank = emptyString.trim().isEmpty();
System.out.println(isBlank);
}
}

In the above code, we have removed the whitespace with the trim method and checked if the string is empty with the isEmpty methodthe isEmpty() method returns true if the string length is 0.

Free Resources