-6
public class StrEqual {
    public static void main(String[] args) {
        String s1 = "hi";
        String s2 = new String("hi");

        System.out.println(s1);
        System.out.println(s2);

        if(s1 == s2){
            System.out.println("s1 and s2 are equal");
        }
        else{
            System.out.println("s1 and s2 are not equal");
        }
    }
}

In the above code s1 and s2 both referring to the string "hi". But why the output of the program is- 's1 and s2 are not equal' ? Thank you

2 Answers2

4

Try

s1.equals(s2);

s1 == s2 compares the object references, not the string contents.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Trevor
  • 13,085
  • 13
  • 76
  • 99
0

The == operator compares the object reference, i.e., their locations in memory. It's like comparing pointers. To have "deep" equality you need to use the equals method.

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94