Strings in Java

I have read that if I use the == operator to compare two string objects,it compares the addresses while the "equals" operator would compare only the contents.
Is it true?

To the following code:

class n
{
public static void main(String art[])
{
String s1="HAARHUIS";
String s2="HAARHUIS";
if(s1==s2)
System.out.println("They are the same");
if(s1.equals(s2))
System.out.println("They are still the same");
}
}

I get:
They are the same
They are still the same
perfect_tranquilityAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
You get that output because the reference happens to be the same. Try this instead:

String s1="HAARHUIS";
String s2= new String("HAARHUIS");
0
 
CEHJCommented:
>>Is it true?

Yes ;-)
0
 
perfect_tranquilityAuthor Commented:
CEHJ,

Bingo!

the new operator forces a new reference string to be created instead of using the old one.
0
 
CEHJCommented:
>>the new operator forces a new reference string to be created instead of using the old one.

Spot on ;-)
0
 
perfect_tranquilityAuthor Commented:
I am happy I am getting the answers.I will be even happier if the answers come with a little bit of more explanation.
Thanks for the support
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.