Example 1: Check if String is Empty or Null
Output
str1 is NULL str2 is EMPTY str3 is neither NULL nor EMPTY
In the above program, we have created
- a null string str1
- an empty string str2
- a string with white spaces str3
- method
isNullEmpty()to check if a string is null or empty
Here, str3 only consists of empty spaces. However, the program doesn't consider it an empty string.
This is because white spaces are treated as characters in Java and the string with white spaces is a regular string.
Now, if we want the program to consider strings with white spaces as empty strings, we can use the trim() method. The method removes all the white spaces present in a string.
Example 2: Check if String with spaces is Empty or Null
Output
str is EMPTY
In the above example, notice the condition to check empty string
else if (str.trim().isEmpty())
Here, we have used the trim() method before isEmpty(). This will
- remove all the white spaces present inside the string
- check if the string is empty
Hence, we get str is EMPTY as output.