Why does first two eg give true when a check done on them using if(x==y) but 3rd and 4th case give false?

eg1: String x = "Hello", y="Hello"

eg2: String x = "Hello";
String y= "Hello";

eg3: String x="Hello";
String y = new String("Hello");

eg4: String x = new String("Hello");
String y = new String("Hello");

Edited by rahul.ch

4 Years
Discussion Span
Last Post by rahul.ch

for checking strings use equal function. == sign doesnt work properly while checking strings.

E.g String a  = "hello";
    a.equal("hello"); // ---- true ----------------

(to clarify Majestic's post:
== works exactly as the language definition says it should, including for Strings. It tests for two references being equal, ie referring to exacty the same object. However, it doesn't do what beginners sometimes think it does, ie test for two Strings containing the same sequence of characters - that needs the equals method)

Because Strings are immutable the compiler is able to optimise String literals by sharing them.
eg1,2: It creates a "hello" string for the first statement, then re-uses the same string for the second. The == test (tests for being the same object) is true.
eg3,4: Using new String explicitly overrides the compiler's optimisation and forces it to create new String object. Now there are two different String objects, so == is false. (But x.equals(y) is true becuase they both contain the same sequence of characters)


Great James and Majestics. I'm more clear on the concept now.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.