How to compare strings in if-else statements?

I wonder if anyone can give me a pointer with some preliminary population in the JSP:

So, I am trying to pre-populate a checkbox depending on the value in the client database record. The checkbox will be checked if there is 1 in the field, another option will be 0, where the checkbox should be empty.

I am currently using this code for input:

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

so it will be:

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

In its current form, it pre-fills everything. However, it is also populated if the field is 0. If I changed it, read:

 if (ISNEWSLETTER == "1") 

then the checkbox is empty, be it 1 or 0.

Am I missing something obvious? I am not a developer, I am in New York, and my support is in Belgium - they all went away for a day.

+4
source share
1 answer

Strings are objects , not primitives . Use equals() , not == / != . == / != will not check if they contain the same value, but if they point to the same object reference. equals() checks to see 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 issue is not related to JSP. You would have the same problem with a regular Java class (where this type of code really belongs).

Alternatively, since they represent numbers, you can also just convert ISNEWSLETTER to int . This is a primitive, so you can use regular == / != . You can optionally convert String to int using Integer#parseInt() . Or, more importantly, if it is actually a logical state (it can only be true or false ), then you better use boolean . You can simply use it directly in the if condition without any comparisons.

+10
source

All Articles