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

String Pooling Question

 
Ed Lance
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me why the LAST System.out.println in the code below prints out true? It's the equals method in the Object class that gets run and that is the same as a == (memory) comparison. Do the Strings get put into the String pool when they are cast up to an Object??

Thanks in advance.



 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me why the LAST System.out.println in the code below prints out true?
The last line prints "true" because both String objects contain the same sequence of characters. It doesn't really have anything to do with pooling in this case, as it's the String's implementation of equals() that's being evaluated.

It's the equals method in the Object class that gets run and that is the same as a == (memory) comparison.
No, it's the equals method in String that gets called ("late binding", polymorphism, and all that rot). See, in order to figure out which instance method to use at runtime, Java looks to the underlying object (a String instance, in this case), rather than the reference type. The String.equals() method overrides the Object's equals() method, and evaluates the string contents for equality.

Hope this helps...
[ August 18, 2005: Message edited by: Steve Morrow ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic