• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 159
  • Last Modified:

How do you figure out of the string isn't equal to anything

In PHP, I could just type:

if(!variable){
   do something
}

And that meant that if there wasn't anything in the variable, then it would do what I wanted.

Can we do that is JSP (especially for strings)?
Similarly, can I make an if statement that check to see if a string IS NOT equal to something?

I know I can;t type:

if(variable != "xyz"){
   do something
}

Thanks,
MD
0
mderbin
Asked:
mderbin
1 Solution
 
ldbkuttyCommented:
In JSP, you do it in this ways:

>> Can we do that is JSP (especially for strings)?
if(variable == null || variable.equals("")) {
  // something ...
}

>> can I make an if statement that check to see if a string IS NOT equal to something?
if(!variable.equals("xyz")) {
  // something ...
}
0
 
CodingExpertsCommented:
You can see all the string related functions here ...
http://www.acunia.com/wonka/javadoc-0.9.5/java/lang/String.html
0
 
KartikShahCommented:
Hi,

>> if(!variable){
>>    do something
>> }

PHP, in the above code check for two cases:
1. Whether the variable has been declared or no
2. If it is declared, then whether it is null or no

In Java/JSP, the first condition is not possible, as Java needs the variables to be declared before hand.

For the second case, you can do the check as:

if(variable == null || "".equals(varialble))
{
    //do something
}
else (!"xyz".equals(variable))
{
   //do something
}

You will notice that I am comparing a string litral to the variable instead of the variable to the string literal, thats just because of good coding practices :)

Kartik
0
 
siliconeagleCommented:
Another equivalet way is :-
if((variable!=null) && !variable.equals("")){...}
because the && oprerator is optimised, if the first condition is false the the second need not be evaluated so the code above does not generate a nullPointerException even when variable is null.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now