0

I am facing an issue in if statement for below code. I am not able to log into if statement even with correct condition. Is my syntax correct?

String NicotineProduct="Not in the last 5 years"

if (NicotineProduct=="No, Never"||NicotineProduct=="Not in the last 5 years"||NicotineProduct=="Not in the last 3 years")
 {    
    if (rateclass=="Pref Best No Nicotine")
             rateclassval=1;
    else if (rateclass=="Pref No Nicotine")
           rateclassval=2;
    else if (rateclass=="Select No Nicotine")
           rateclassval=3;
    else if (rateclass=="Standard No Nicotine")
           rateclassval=4;
 }
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
vikas
  • 1
  • 1
  • No, your syntax is not correct in that it does not bare the semantics you want. Always use [String.equals()](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals%28java.lang.Object%29) for String comparisons; everything else means asking for trouble. – JimmyB Oct 10 '14 at 13:59

2 Answers2

0

Always use .equals for String comparisons:

if (NicotineProduct.equals("No, Never")||NicotineProduct.equals("Not in the last 5 years")||NicotineProduct.equals("Not in the last 3 years")) {
    if (rateclass.equals("Pref Best No Nicotine"))
         rateclassval=1;
    else if (rateclass.equals("Pref No Nicotine"))
         rateclassval=2;
    else if (rateclass.equals("Select No Nicotine"))
         rateclassval=3;
    else if (rateclass.equals("Standard No Nicotine"))
         rateclassval=4;
}

See this other question/answer:

How do I compare strings in Java?

Community
  • 1
  • 1
michaelgulak
  • 631
  • 1
  • 6
  • 14
0

String.equals() is the preferred way for comparing string values.

VMi
  • 346
  • 3
  • 16