EugeneP
EugeneP

Reputation: 12003

One step check for null value & emptiness of a string

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

Answers (8)

its not String. it should be Strings. as an example:

if(!Strings.isNullOrEmpty()

Upvotes: 0

Daly
Daly

Reputation: 879

Spring

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

Noah
Noah

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

Joel
Joel

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

Sophia Price
Sophia Price

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

Ahmed Rezk
Ahmed Rezk

Reputation: 301

if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}

Upvotes: 5

E A
E A

Reputation: 1234

use org.apache.commons.lang.StringUtils, the method StringUtils.isNotBlank check both nullity and emptiness.

Upvotes: 1

DerMike
DerMike

Reputation: 16190

In the jakarta commons there is a StringUtils.isEmpty(String).

Upvotes: 4

Related Questions