I'm unable to compare two strings using the following code:
I have a string named "gender" which will have "Male" or "Female" as its value.
if(gender == "Male") salutation ="Mr."; if(gender == "Female") salutation ="Ms.";
This didn't work, so I tried the following:
String g1="Male"; String g2="Female"; if(gender.equals(g1)) salutation ="Mr."; if(gender.equals(g2)) salutation ="Ms.";
Again, it didn't work. Can someone please tell me how to compare string values using the if statement.
Try this
if(gender.equals("Male")) salutation ="Mr."; if(gender.equals("Female")) salutation ="Ms.";
Also remove ;
(semi-colon ) in your if statement
if(gender.equals(g1));
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object references, not the content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With