Reputation: 12003
I have a setter method.
Then when another (say generate) method is run, I need to check the value of my fields. So in the case of String property, I need to know if it contains the value or if it was not set. So it may be null, "" or something meaningful, there are 3 possibilities. And it is rather boring to check first for a null value :
if (s != null)
then for an empty String
if (!s.isEmpty())
is there a one-step check here? You can tell me that I can initialize my String field with an empty String. [ IS IT COMMON? ] But what if someone passes a null value to the setter method setS? so do we always have to check if the Object value is null or not before doing something with that object?
Well, yes a setter method can check it's values and also a getter method can return a non-null value if the field is null. But is it the only solution? It 's too much work in getters & setters for a programmer to do!
Upvotes: 17
Views: 36356
Reputation: 901
its not String. it should be Strings. as an example:
if(!Strings.isNullOrEmpty()
Upvotes: 0
Reputation: 879
Spring provides the class org.springframework.util.StringUtils which includes these relevant methods.
hasText(String s)
Returns true if and only if a String
or CharSequence
contains a character which is not a space.
Example:
StringUtils.hasText(null) = false
StringUtils.hasText("") = false
StringUtils.hasText(" ") = false
StringUtils.hasText("12345") = true
StringUtils.hasText(" 12345 ") = true
hasLength(String s)
Returns true if and only if a String
or CharSequence
contains any characters, spaces included.
Example:
StringUtils.hasLength(null) = false
StringUtils.hasLength("") = false
StringUtils.hasLength(" ") = true
StringUtils.hasLength("Hello") = true
In the case of the question, hasText
would be the best option.
Upvotes: 0
Reputation: 15320
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.
Upvotes: 0
Reputation: 30146
Commons library, StringUtils.isBlank() or StringUtils.isEmtpy().
isEmpty is equivalent to
s == null || s.length() == 0
isBlank is equivalent to
s == null || s.trim().length() == 0
Upvotes: 18
Reputation: 958
Add maven dependency for com.google.guava
Then in your code:
import com.google.common.base.Strings;
if(!Strings.isNullOrEmpty(s)) {
// Do stuff here
}
Upvotes: 0
Reputation: 301
if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}
Upvotes: 5
Reputation: 1234
use org.apache.commons.lang.StringUtils, the method StringUtils.isNotBlank check both nullity and emptiness.
Upvotes: 1