Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark ""abc"=="abc"?" Watch ""abc"=="abc"?" New topic
Author

"abc"=="abc"?

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
"abc"=="abc"
true or false? And why?
Thanks!
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
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).]


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Nov 22, 2008
Posts: 18944
Thanks a lot! I think I got the point!
 
Consider Paul's rocket mass heater.
 
subject: "abc"=="abc"?
 
Similar Threads
overloading n overriding
EL Question...
replacing a regex wild card
Whats wrong with this code ?
printing in table format using logic:iterate and bean:write