Java isBlank() method is a String class method added into Java 11 version. This method is used to test a string whether it is empty or contains only whitespaces codepoints.
It returns either true or false. If the string is empty or contains whitespaces, it returns true, otherwise false.
public boolean isBlank()
Lets have an example to understand this method. Here we are using empty string to check whether it is blank or not. Since it returns true for empty string, so here it does the same.
class Demo{
public static void main(String[] args) {
// empty string
String str = " ";
// isBlank
boolean result = str.isBlank();
System.out.println(result);
}
}
Output:
true
In this example, we are using some whitespace codepoints like: new line, tab etc to check whether the isBlank() method returns true or not. See the below example.
class Demo{
public static void main(String[] args) {
// newline
String str = "\n";
// tab
String str2 = "\t";
// carriage return
String str3 = "\r";
// isBlank
boolean result = str.isBlank();
System.out.println(result);
result = str2.isBlank();
System.out.println(result);
result = str3.isBlank();
System.out.println(result);
}
}
Output:
true
true
true
It returns false if string is non empty whether it includes spaces or not. See the below example.
class Demo{
public static void main(String[] args) {
// non empty string
String str = "hello";
// string with spaces
String str2 = "hello ";
// carriage return
String str3 = " hello ";
// isBlank
boolean result = str.isBlank();
System.out.println(result);
result = str2.isBlank();
System.out.println(result);
result = str3.isBlank();
System.out.println(result);
}
}
Output:
false
false
false
List of whitespace codepoints that are considered as blank by the String isBlank method.
'\t' - TAB CHARACTER
'\n' - NEW LINE CHARACTER
'\u' - VERTICAL TABULATION
'\f' - FORM FEED CHARACTER
'\r' - CARRIAGE RETURN CHARACTER
Java Character class has a method isWhitespace() to check whether a character is a whitespace or not. We can use it to ensure the charater is a whitespace codepoint. See the below example.
class Demo{
public static void main(String[] args) {
String str = "\n";
// is whitespace char
boolean result = Character.isWhitespace('\n');
System.out.println("Is empty: "+result);
// isBlank
result = str.isBlank();
System.out.println("Is blank: "+result);
}
}
Output:
Is empty: true
Is blank: true
Well, in this topic, we learnt about the new isBlank() method of String class. We go through the whitespace codepoins that are special characters and saw the behaviour of isBlank() method including use of iswhitespace() method.
If we missed something, you can suggest us at - info.javaexercise.com