In Java, why does String == String evaluate to true inside a method (as opposed to using .equals())?

104 views Asked by At

If I have:

Boolean isEqual = compare("Hello World");

Boolean compare(String c) {
    String s = "Hello World";
    return s == c;
}

In my experience, this returns true. Why?

1

There are 1 answers

2
NimChimpsky On

because its a string literal that has been interned, the same instance is used.

Use new String("Hello World") to make it false.

Also asked many many many times before on here