Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison - Android [duplicate]

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.

like image 552
Raghav Kumar Avatar asked Apr 22 '13 09:04

Raghav Kumar


1 Answers

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.

like image 136
Linga Avatar answered Oct 02 '22 05:10

Linga