In Java 11, a new method called isBlank()
was added in the String class.
The isBlank()
method will return true
in the below cases:
public class HelloWorld {public static void main(String[] args) {String emptyString = "";System.out.println(emptyString.isBlank()); // trueString emptyStringWithSpace = " ";System.out.println(emptyStringWithSpace.isBlank()); // trueString emptyStringWithTabSpace = " \n \t ";System.out.println(emptyStringWithTabSpace.isBlank()); // trueString 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