user3592151
user3592151

Reputation: 11

check the string for empty or null values in JSP?

I am working in JSP forms and i am sorting the results on the basis of user selection criteria. now the problem is in the if condition which only falls in the first condition either the I select the city or not

My sample code is below:

if (user_city !=null || user_city !="") 
{  
  out.print("first condition is true"); 
}
else 
{
  out.print("second condition is true");
}

Why doesn't this work?

Upvotes: 1

Views: 15431

Answers (2)

cbojar
cbojar

Reputation: 178

You are using || when you probably want &&. In your original code, if user_city is null, it will try the second comparison, where null != "" is true. This makes the whole thing true, which seems contrary to your intention. It would also be good to take the other advice and make the comparison:

if(user_city != null && !user_city.trim().isEmpty()) {...

Upvotes: 2

Braj
Braj

Reputation: 46871

Trim user_city before checking with empty string

if (user_city != null && !"".equals(user_city.trim())) {
    out.print("user_city is not null and not empty");
} else {
    out.print("user_city is either null or empty");
}

Upvotes: 0

Related Questions