We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,437 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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");

3
Contributors
3
Replies
3 Hours
Discussion Span
8 Months Ago
Last Updated
4
Views
Question
Answered
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
Moderator
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

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0655 seconds using 2.74MB