Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String isNullOrEmpty in Java? [duplicate]

Tags:

java

string

People also ask

What does string isNullOrEmpty return?

The C# IsNullOrEmpty() method is used to check whether the specified string is null or an Empty string. It returns a boolean value either true or false.

How do you check if a string is not empty?

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

Does string isEmpty check for null?

isEmpty(<string>) Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.


  • StringUtils.isEmpty(str) or StringUtils.isNotEmpty(str)
  • StringUtils.isBlank(str) or StringUtils.isNotBlank(str)

from Apache commons-lang.

The difference between empty and blank is : a string consisted of whitespaces only is blank but isn't empty.

I generally prefer using apache-commons if possible, instead of writing my own utility methods, although that is also plausible for simple ones like these.


If you are doing android development, you can use:

TextUtils.isEmpty (CharSequence str) 

Added in API level 1 Returns true if the string is null or 0-length.


com.google.common.base.Strings.isNullOrEmpty(String string) from Google Guava


No, which is why so many other libraries have their own copy :)


You can add one

public static boolean isNullOrBlank(String param) { 
    return param == null || param.trim().length() == 0;
}

I have

public static boolean isSet(String param) { 
    // doesn't ignore spaces, but does save an object creation.
    return param != null && param.length() != 0; 
}

To check if a string got any characters, ie. not null or whitespaces, check StringUtils.hasText-method (if you are using Spring of course)

Example:

StringUtils.hasText(null) == false
StringUtils.hasText("") == false
StringUtils.hasText(" ") == false
StringUtils.hasText("12345") == true
StringUtils.hasText(" 12345 ") == true