In this tutorial, you will learn how to check if a Java string is empty, null or consist of a whitespace character. To learn more about Java, please check the Java category page.
Let’s start with a simple example that checks if String is null.
Check If Java String is Null
If a String variable in Java has not been initialized, its value is null. You can also assign a null value to a variable explicitly. Either way, if you need to check if the variable is null you do it with a double equal sign(==).
String name=null; if(name == null) { System.out.println("Variable name is not initialized "); }
Check If Java String is Empty
An empty string in Java is a string of zero length. The main difference between an empty string and a null string is that an empty string is a string instance of zero length, whereas a null string has no value at all.
Using isEmpty() method
To check if the Java string is empty, you can use the isEmpty() method.
String name = ""; if(name.isEmpty()) { System.out.println("Variable name is empty "); }
Checking the String length
If you look at the implementation of the isEmpty() method in Java, you will see that it simply checks if the length of a string is zero. So to check if the string value is empty, you can either use the isEmpty() method or explicitly check the length of a string.
String name = ""; if(name.length()==0) { System.out.println("Variable name is empty "); }
Check if the string is not null and not empty
Either way, it is always better to first check if the String is not null.
String name = ""; if(name!=null && name.length()==0) { System.out.println("Variable name is empty "); }
Check if Java String is Whitespace or Blank
A Java String can also be blank or consist of only whitespace characters. For example, the following string is blank.
String name=" ";
To check if Java String is blank, we use the isBlank() method.
public class App { public static void main(String args[]) { if(name!=null && name.isBlank()) { System.out.println("The name variable is blank"); } } }
Check if Java String is Null, Empty or Blank
Now that you know how to check if the Java string is null, empty or blank, you can write your own way to check for these conditions. But one of the ways you can put all the above code examples together is below:
public class App { public static void main(String args[]) { String name = " "; if(name==null || name.trim().isEmpty()) { System.out.println("The name variable has no value"); } } }
I hope this tutorial was helpful to you. There are many more Java tutorials on this website. And if you are interested in learning how to build and test Spring Boot Microservices, then have a look at the following tutorials.
- Building Spring Boot Web Services,
- Building Spring Boot Microservices and Spring Cloud,
- OAuth in Spring Boot applications
- Unit Testing Java applications
Happy learning!