Solved

Strings in Java

Posted on 2004-09-16
5
171 Views
Last Modified: 2010-03-31
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
0
Comment
Question by:perfect_tranquility
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12079967
>>Is it true?

Yes ;-)
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 12079978
You get that output because the reference happens to be the same. Try this instead:

String s1="HAARHUIS";
String s2= new String("HAARHUIS");
0
 

Author Comment

by:perfect_tranquility
ID: 12080011
CEHJ,

Bingo!

the new operator forces a new reference string to be created instead of using the old one.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12080026
>>the new operator forces a new reference string to be created instead of using the old one.

Spot on ;-)
0
 

Author Comment

by:perfect_tranquility
ID: 12080029
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This video teaches viewers about errors in exception handling.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question