Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String doubt..

 
suresh mandalapu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s=new String("suresh");

here s is a reference..
and the statement

if(s=="suresh") rerurns false.since s contains a bit stream and the other one is a string..//no doubt here

but when we do like this

String s="suresh";//here also s is an object and contains bit stream only..
if(s=="suresh") shuold return false..because s is an object and contains a bit stream.
but it is returning true..
what is the reason?
in the second case if i print s it is directly printing the suresh..
but my doubt is s contains bit stream only..it should print some other value(bit stream)
what is the diference between 1st case and 2nd case?

 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a frequently asked question here at Ranch. When you say 'new String("suresh")' you will ended up with two string objects in the heap one referenced by the constant pool (of course this is if you didn't have any literal defined as "suresh" prior to this in your code), and one created using the new keyword . That's why you are getting false since "==" checks whether two references refer to the same object rather than the content. This Java Ranch Journal explains the concept.
 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All your question are answered HERE
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
suresh mandalapu wrote:if(s=="suresh") rerurns false.since s contains a bit stream and the other one is a string..//no doubt here

A "bit stream"? This is not the reason that == does not work to compare String objects.

The == operator, when used on variables of non-primitive types, checks for reference equality, which means that it checks if the things on the left and right side of the == refer to the exact same object.

If you have two different String objects with the same content and you compare them with ==, the result will be false because they are two distinct objects (despite that they have the same content).

Text between double quotes in Java source code, such as "suresh", is regarded as a String object, exactly the same as a variable that's declared to be of type String. There's no such thing as a "bit stream".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic