• Post Reply Bookmark Topic Watch Topic
  • New Topic

"==" vs equals()  RSS feed

 
Aleksey Movchan
Ranch Hand
Posts: 49
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Up to this day I thought "==" operator checks if two objects refer to the same address.
Today I checked this code:

So why does it print "true" and don't change s1 variable after changing s2? How does "==" work for strings?
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have an FAQ about the == operator; have a look, but all that will tell you at the moment is that the two String references point to the same object. So, search the Ranch for “Corey McGlone Strings Literally” and you shou‍ld find this. That will tell you all you need to know, even though it is an old article.
Briefly: whenever the class loaders encounter a String literal, they check whether it is already on the heap, and if so, reuse the value on the heap. So the two instances of "abc" are used as one object.
After you printed same, you changed one of the references to point to a different String object, but you left the other unchanged. So s₁ → "abc" but s₂ → "abdd".
 
Aleksey Movchan
Ranch Hand
Posts: 49
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!