• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
Bartenders:
  • Himai Minh
  • Carey Brown
  • Frits Walraven

Rationale for why object reference equality is false

 
Ranch Hand
Posts: 110
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear all,
I keep on getting caught out when it comes to object reference equality. I know that String is immutable and StringBuilder is mutable. Shouldn't s1 and s2 have the same reference on the heap? sb vs (s1 or s2) would be different?

/* What will be the result of compiling and executing the below class?
  A) Compilation error
  B) An exception is thrown at runtime
  C) false                                 [CORRECT]
  D) true                                  [WRONG ANSWER]

*/

public class _40_Question_StringBuilder {

   public static void main(String[] args) {
       StringBuilder sb = new StringBuilder("Java");       // obj ref 1
       String s1 = sb.toString();                          // obj ref 2
       String s2 = sb.toString();                          // obj ref 3

       System.out.println(System.identityHashCode(sb));    // 356573597
       System.out.println(System.identityHashCode(s1));    // 1735600054
       System.out.println(System.identityHashCode(s2));    // 21685669

       System.out.println(s1 == s2);   // false
   }

}
 
Saloon Keeper
Posts: 13078
281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Every time you call sb.toString(), it creates a new String instance. The reason for this is easy to understand: The string builder doesn't keep a reference to the previous string object it created, so it can't return the same string object when you call toString() a second time.
 
Clemonte Johnstone
Ranch Hand
Posts: 110
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Every time you call sb.toString(), it creates a new String instance. The reason for this is easy to understand: The string builder doesn't keep a reference to the previous string object it created, so it can't return the same string object when you call toString() a second time.



Many thanks
 
reply
    Bookmark Topic Watch Topic
  • New Topic