isBlank() vs isEmpty() in String class Java

isBlank() is a new method introduced in String class in Java. By naming isBlank() and isEmpty() methods look similar to each other, but there is a slight difference between them –

isBlank() returns true for the string having only white space characters whereas isEmpty() will return false for such strings.

Let us understand the difference with help of code –

public class EmptyBlank {

	public static void main(String[] args) {
		
		String str1 = "";
		System.out.println(str1.isEmpty());     //true
		System.out.println(str1.isBlank());     //true 
		
		
		// single white space character
		String str2 = "\n";
		System.out.println(str2.isEmpty());     //false
		System.out.println(str2.isBlank());     //true
		
		
		// multiple white space character
		String str3 = "\n\t";
		System.out.println(str3.isEmpty());     //false
		System.out.println(str3.isBlank());     //true
		
		
		String str4 = "Tech4Humans";
		System.out.println(str4.isEmpty());     //false
		System.out.println(str4.isBlank());     //false
	}

}

Output

true
true
false
true
false
true
false
false

Let us look at another method in Java 11 – strip method.

Leave a Comment