String comparison doubts
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");
Related Article: string to xml object java
is a Java discussion thread by innspiron that has 6 replies and was last updated 1 year ago.
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
for checking strings use equal function. == sign doesnt work properly while checking strings.
E.g String a = "hello";
a.equal("hello"); // ---- true ----------------
Majestics
Practically a Master Poster
696 posts since Jul 2007
Reputation Points: 209
Solved Threads: 66
Skill Endorsements: 5
(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)
JamesCherrill
... trying to help
8,527 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
Great James and Majestics. I'm more clear on the concept now.
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 8 Months Ago by
Majestics
and
JamesCherrill