This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"abc"=="abc"?

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"abc"=="abc"
true or false? And why?
Thanks!
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is true.
"abc" is a string because it is in double quotes.
There are two such string objects one on the left hand side and another one on the right hand side.
When this expression is evaluated, JVM tries to create two strings. Because the strings are identical, JVM reuses the string "abc" already created in the string pool instead of creating a duplicate one( very important concept ).
So the reference of the string on the left hand side is the same as the reference of the string on the right hand side. Hence == returns true.
Is it clear?
Ajith


[This message has been edited by Ajith Kallambella (edited July 14, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True. String literals are stored in a string pool. Since String objects are immutable, this optimzation mechanism is safe to do. So, "abc" and "abc" can reference the same "abc" in the pool.
But, beware of this:
String s1 = new String("abc");
String s2 = "abc";
s1 == s2 is false because s1 is explicitly created on the heap.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot! I think I got the point!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic