File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: "abc"=="abc"?