Correct way to check for null or empty or string containing only spaces is like this:
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
Answer from Pradeep Simha on Stack OverflowCorrect way to check for null or empty or string containing only spaces is like this:
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).
Example:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
Shorter (efficient) way to check if a string is null or empty?
Best Way to Check if a String is Null or Empty in Java - TestMu AI Community
java - Check for empty string null? - Stack Overflow
What is the correct way to check if a String is empty or null in Java, and how can I avoid potential errors? - TestMu AI Community
Videos
The value null is not equal to the String "null". null means that a given object has not been assigned a value, where the String "null" is a valid object. It contains the characters n u l l, which is a valid value for a String. You need to also check if the value is the literal string "null" in order to do what you want.
Correct Check
return value == null || value.isEmpty() || value.equals("null") ;
If you want to still maintain "null" as a valid username, then change whatever is sending the json to the following format, which should be interpreted as a literal null rather than a String with content "null"
"userId":null
"null" is not the same as null.
"null" is a string 4 characters in length of the word "null".
null (no quotes) is just that--nothing.