Click to See Complete Forum and Search --> : String comparison


phoebeching
04-12-2007, 08:06 PM
Hi Good day,

<% String sDepartment = "";
sDepartment = infobean.getDEPARTMENT();
if (sDepartment == "AD")
out.write(sDepartment);
else
out.write("Anything");
%>

I was able to retrieve the data for sDepartment but the comparison was not successfully compared. I already trim the sDepartment and set it to capital letter but it still not working. I did a testing by creating a constant and do a comparison and it works.
Can someone help? Thanks in advanced.

phoebe.

Khalid Ali
04-13-2007, 11:06 AM
== is used for mostly primitive datatype comparisons. String is an object not a primitive data type for this reason, you always use obj.equals() method.
hence your test should look like this
if (sDepartment.equals("AD"){
//do whatever
}

Kostas Zotos
04-14-2007, 09:35 AM
Hi,

Khalid Ali: I agree with you..

Three common methods for String comparison i think are:

if( sDepartment.equals("AD") ){
out.write(sDepartment);
}


if( sDepartment.equalsIgnoreCase("AD") ){ //comparison independent of the string case_
//_(no matter if used: lower case, UPPER CASE, mixed mode etc)
out.write(sDepartment);
}


if( sDepartment.compareTo("AD")==0 ){
out.write(sDepartment);
}

Kostas

agent_x91
04-15-2007, 03:24 PM
The best one to use is Object.equals(Object), which should be used for all object comparisons. String.equalsIgnoreCase(String) is also very useful when needing to ignore cases in strings. The == operator should never be used for String or any other Object comparison.

Regular expressions are useful as well.