lang3
Check empty string
In this example we shall show you how to check if a String is empty. We are using the org.apache.commons.lang3.StringUtils class, that provides operations on String that are null safe.. To check if a String is empty one should perform the following steps:
- Create a few String objects.
- Use the
isBlank(String s)method to check if a String contains text. - Use the
isEmpty(String s)method to check if a String contains text, too. - You can also use the
isBlank(String s)andisEmpty(String s)methods,
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
import org.apache.commons.lang3.StringUtils;
public class emptyStringExample {
public static void main(String[] args) {
String string1 = null;
String string2 = "";
String string3 = "ttt";
String string4 = "JavaCodegeeks";
System.out.println("string1 blank = " + StringUtils.isBlank(string1));
System.out.println("string2 blank = " + StringUtils.isBlank(string2));
System.out.println("string3 blank = " + StringUtils.isBlank(string3));
System.out.println("string4 blank = " + StringUtils.isBlank(string4));
System.out.println("string1 not blank = " + StringUtils.isNotBlank(string1));
System.out.println("string2 not blank = " + StringUtils.isNotBlank(string2));
System.out.println("string3 not blank = " + StringUtils.isNotBlank(string3));
System.out.println("string4 not blank = " + StringUtils.isNotBlank(string4));
System.out.println("string1 empty = " + StringUtils.isEmpty(string1));
System.out.println("string2 empty = " + StringUtils.isEmpty(string2));
System.out.println("string3 empty = " + StringUtils.isEmpty(string3));
System.out.println("string4 empty = " + StringUtils.isEmpty(string4));
System.out.println("string1 not empty = " + StringUtils.isNotEmpty(string1));
System.out.println("string2 not empty = " + StringUtils.isNotEmpty(string2));
System.out.println("string3 not empty = " + StringUtils.isNotEmpty(string3));
System.out.println("string4 not empty = " + StringUtils.isNotEmpty(string4));
}
}
Output:
string1 blank = true
string2 blank = true
string3 blank = true
string4 blank = false
string1 not blank = false
string2 not blank = false
string3 not blank = false
string4 not blank = true
string1 empty = true
string2 empty = true
string3 empty = false
string4 empty = false
string1 not empty = false
string2 not empty = false
string3 not empty = true
string4 not empty = true
This was an example of how to check if a String is empty in Java.

The code snippet output for the isBlank and isNotBlank methods is slightly incorrect.
Here is what their two outputs for string3 should be:
The output of ‘string3 blank = ‘ false.
The output of ‘string3 not blank = ‘ true.