Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Strings in if-else statements?

I wonder if anyone could give me a pointer with some pre-population in JSP:

So I am attempting to pre-populate a checkbox depending on the value in the customers database record. The checkbox would be checked if there is a 1 in the field, the other option would be a 0 - where the checkbox should be empty.

I am currently using this code within the input:

<%if (UPDATEDPREFERENCES != null)
{ 
    if (ISNEWSLETTER != "0") {
        out.println("checked");
    } 
}
%>

so it would be:

<input type='checkbox' class="newsletter" name='temp_ISNEWSLETTER_FIELD' id="temp_ISNEWSLETTER_FIELD" <%if (UPDATEDPREFERENCES != null)
{ 
    if (ISNEWSLETTER != "0") {
        out.println("checked");
    } 
}
%>/>

As it stands, it pre-populates fine. However, it also populates if the field is 0. If I change it to read:

if (ISNEWSLETTER == "1")

then the checkbox is empty whether it's a 1 or 0.

Am I missing something obvious? I am not a developer, I am in NYC and my support is in Belgium - they've all left for the day.

like image 575
Gary Deuces Rozanski Avatar asked Oct 06 '11 16:10

Gary Deuces Rozanski


1 Answers

Strings are objects, not primitives. Use equals(), not ==/!=. The ==/!= won't check if they contain the same value, but if they point to the same object reference. The equals() will check if they contain the same value.

So, instead of if (ISNEWSLETTER != "0") you should use

if (!ISNEWSLETTER.equals("0"))

and instead of if (ISNEWSLETTER == "1") you should use

if (ISNEWSLETTER.equals("1"))

This problem is not related to JSP. You would have exactly the same problem when doing so in a normal Java class (where this kind of code actually belongs).

As an alternative, since they represent numbers, you could also just convert ISNEWSLETTER to an int. It's a primitive, so you should be able to use ==/!= the usual way. You can if necessary convert a String to an int using Integer#parseInt(). Or, even more, if it actually represents a boolean state (it can only be true or false), then you should rather use boolean instead. You can just use it straight in the if condition without any need for comparisons.

like image 157
BalusC Avatar answered Sep 27 '22 22:09

BalusC