Why doesn’t == work on String? [duplicate]

Use the String.equals(String otherString) function to compare strings, not the == operator.

This is because the == operator only compares object references, while
the String.equals() method compares both String‘s values i.e. the sequence of characters that make up each String.

equals() method from Source code of String:

        public boolean equals(Object anObject) {
1013        if (this == anObject) {
1014            return true;
1015        }
1016        if (anObject instanceof String) {
1017            String anotherString = (String)anObject;
1018            int n = count;
1019            if (n == anotherString.count) {
1020                char v1[] = value;
1021                char v2[] = anotherString.value;
1022                int i = offset;
1023                int j = anotherString.offset;
1024                while (n-- != 0) {
1025                    if (v1[i++] != v2[j++])
1026                        return false;
1027                }
1028                return true;
1029            }
1030        }
1031        return false;
1032    }

So you should write

if(gender.equals("boy")){

}

or to comapre with regardless of case

if(gender.equalsIgnoreCase("boy")){

}

and for null safety

if("boy".equals(gender)){

}

Future reference:

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

Here s1 == s2 == s3 but s4 != s5

Where as

anyOfAbove.equals(anyOtherOfAbove); //true

Leave a Comment