mderbin
asked on
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
>> 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
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.
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.
http://www.acunia.com/wonka/javadoc-0.9.5/java/lang/String.html