How can I check whether a string is not null and not empty?
public void doStuff(String str)
{
if (str != null && str != \"**here I want to check
To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank()
(as in what is whitespace or not).
Guava's version of Commons Lang isBlank
would be:
Strings.nullToEmpty(str).trim().isEmpty()
I will say code that doesn't allow ""
(empty) AND null
is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null
makes sense (although for SQL I can understand as SQL/HQL is weird about ''
).
You should use org.apache.commons.lang3.StringUtils.isNotBlank()
or org.apache.commons.lang3.StringUtils.isNotEmpty
. The decision between these two is based on what you actually want to check for.
The isNotBlank() checks that the input parameter is:
The isNotEmpty() checks only that the input parameter is
Simple solution :
private boolean stringNotEmptyOrNull(String st) {
return st != null && !st.isEmpty();
}
In case you need to validate your method parameters you can use follow simple method
public class StringUtils {
static boolean anyEmptyString(String ... strings) {
return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
}
}
Example:
public String concatenate(String firstName, String lastName) {
if(StringUtils.anyBlankString(firstName, lastName)) {
throw new IllegalArgumentException("Empty field found");
}
return firstName + " " + lastName;
}
As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;
public List<Employee> findEmployees(String str, int dep) {
Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
/** code here **/
}
May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.
If you are using Spring Boot then below code will do the Job
StringUtils.hasLength(str)