In this post, we will learn “How to check blank or empty string in Java 11?”. Java 11 introduced a new method called isBlank to determine if a given string is blank or empty.
Here, we are going to learn following things:
- What is isBlank() method?
- How to use it?
- How is it different from isEmpty() method?
Check blank or empty string in Java 11...!!! Share on X
Let’s Begin,
1. What is isBlank() method?
isBlank() is a boolean method of String class.
This method returns true
if the string is empty or contains only white space, otherwise false
.
2. How to use it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Check_Blank_Empty_String_Java11 { public static void main(String[] args) { String s1 = "Techndeck"; String s2 = " Techndeck "; String s3 = " "; String s4 = ""; System.out.println(s1.isBlank()); //false System.out.println(s2.isBlank()); //false System.out.println(s3.isBlank()); //true System.out.println(s4.isBlank()); //true } } |
1 2 3 4 | false false true true |
2. How is it different from isEmpty() method?
isEmpty() is a boolean method of String class similar to isBlank method and they both performs the same task of checking whether the string is blank or empty. BUT, there is a difference between the two.
isEmpty() method returns true
if, and only if, length of the string is 0
. while on the other hand, isBlank method checks for non-white characters only, it doesn’t check the string length.
Let’s see several examples of isBlank vs isEmpty usage and notice the differences.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Blank_vs_Empty_String_Java11 { public static void main(String[] args) { String s1 = "Techndeck"; String s2 = " Techndeck "; String s3 = " "; String s4 = ""; System.out.println(s1.isBlank()); //false System.out.println(s1.isEmpty()); //false System.out.println(s2.isBlank()); //false System.out.println(s2.isEmpty()); //false System.out.println(s3.isBlank()); //true System.out.println(s3.isEmpty()); //false System.out.println(s4.isBlank()); //true System.out.println(s4.isEmpty()); //true } } |
Output:
1 2 3 4 5 6 7 8 | false false false false true false true true |
Check blank or empty string in Java 11...!!! Share on X
Do you like this Post? – then check my other helpful posts: