This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"abc"=="abc"?

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
"abc"=="abc"
true or false? And why?
Thanks!
 
Ajith Kallambella
Sheriff
Posts: 5782
  • 0
  • 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
  • 0
  • 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
  • 0
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot! I think I got the point!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic