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.
This one work for me:
Actually every code runs well here, but your probleme probably come from your
gender
variable. Did you try to do a simpleSystem.out.println(gender);
before the comparaison ?Try it:
Try this
Also remove
;
(semi-colon ) in your if statementIn 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.
try this.
Output:
Your
gender == "Male"
is actually comparing the object references for the objectgender
and a different objectMale
. What you have to use is the.equals()
method to compare the value of the objects.