Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Comparison

 
Vikram Ramaswamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, sorry if this is a lame question that I already ought to know (or has already been answered)
Given Strings s1 and s2, I was wondering what the real difference between s1 == s2 and s1.equals(s2) is


In my understanding, s1 == s2 must fail since they are two separate objects, but when I run the code, both if conditions pass & Hash codes are equal too...
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In my understanding, s1 == s2 must fail since they are two separate objects,


NO they are 2 references to *same* String literal in String Constant Pool.

check Javaranch Journal.
 
Vikram Ramaswamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now. Thank you.
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

you are Welcome. and Indeed Welcome to Javaranch
 
Rene Larsen
Ranch Hand
Posts: 1179
Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to do the same check with Integer, Byte or Long - you will see that there are a Constant Pool limit of values in the range -128 to 127

Meaning the == will only work in the range -128 to 127
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rene Larsen wrote:Meaning the == will only work in the range -128 to 127

integers not being equal to one another
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic