Check if a String is Empty or Null in Java
In Java, checking whether a string is null or empty is extremely important. Many runtime errors occur when developers try to access methods on a null string.
Understanding the difference between null and an empty string helps you write safer and bug-free programs.
Difference Between Null and Empty String
- null → The string does not refer to any object.
- Empty string ("") → The string exists but contains no characters.
Why Proper Checking is Important
Calling methods like length() or isEmpty() on a null string will cause a
NullPointerException.
Therefore, the null check must always come first.
How the Logic Works
- Check if the string is
null. - If not null, check if its length is zero.
- Decide whether the string is null, empty, or valid.
Example 1
Input: null
Result: String is Null
Example 2
Input: ""
Result: String is Empty
Example 3
Input: "Java"
Result: String is Not Empty
Java Program to Check if String is Null or Empty
import java.util.Scanner;
public class CheckNullOrEmpty {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string (type nothing for empty): ");
String str = sc.nextLine();
if (str == null) {
System.out.println("String is Null");
}
else if (str.length() == 0) {
System.out.println("String is Empty");
}
else {
System.out.println("String is Not Empty");
}
}
}
Sample Output
Enter a string (type nothing for empty):
String is Empty
Enter a string (type nothing for empty): Hello
String is Not Empty
Important Notes
- Always check for
nullbefore checking length. - An empty string still occupies memory.
- Blank strings (spaces only) are different from empty strings.
Practice Challenges
- Modify the program to detect blank strings (only spaces).
- Check string emptiness without using
length(). - Write a utility method that safely checks null and empty values.
Mastering null and empty string checks is essential for writing robust Java applications.