Java String isBlank() method returns true if the string is empty or contains only white spaces codepoints. This utility method was added to String class in Java 11 release.
Table of Contents
White Space Unicode Code Points in Java
Java considers the following characters as white space. Note that this is not an extensive list and there are high chances that I might have missed some special white space Unicode characters.
- \n or \u005Cn – newline character
- \t or \u005ct – tab character
- \r or \u005Cr – carriage return
- \u005ct – horizontal tabulation
- \u005Cn – line feed
- \u000B – vertical tabulation
- \u005Cf – form feed
- \u001C – file separator
- \u001D – group separator
- \u001E – record separator
- \u001F – unit separator
Java String isBlank() Examples
Let’s look at some examples of isBlank() method.
1. String is empty
jshell> String str = "";
str ==> ""
jshell> str.isBlank();
$32 ==> true
2. The string contains only tab, newline, carriage return characters
jshell> String str = " \t ";
str ==> " \t "
jshell> str.isBlank()
$34 ==> true
jshell> str = " \n\n\r ";
str ==> " \n\n\r "
jshell> str.isBlank()
$36 ==> true
3. The string contains special white space characters
jshell> char[] chars = { '\u005ct', '\u005Cn', '\u000B', '\u005Cf', '\u005Cr', '\u001C', '\u001D', '\u001E', '\u001F' };
chars ==> char[9] { '\t', '\n', '\013', '\f', '\r', '\034', '\035', '\036', '\037' }
jshell> String str = new String(chars);
str ==> "\t\n\013\f\r\034\035\036\037"
jshell> str.isBlank();
$39 ==> true
4. The string contains non-white space characters
jshell> String str = " H ";
str ==> " H "
jshell> str.isBlank();
$41 ==> false
String isBlank() vs isEmpty()
- String isBlank() is used to test if the string is empty or contains only white space characters.
- String isEmpty() method is used to test if the string is empty or not.