• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

* Byte == comparision

 
Deepti Dixit
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why does this give 'False' ?
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call toString() on an object, internally the code creates a new String instance and returns this to the caller; every time you call toString() a new String instance is created.
Since it's a new String object each time, and since the == operator tests if two objects are the *same object*, this test returns FALSE since the two Strings are different objects.
This again highlights the importance of using the equals() method to compare two objects. ONLY use the == operator if you are comparing primatives, OR if reference comparison is what you really want.
Rob
[ January 11, 2002: Message edited by: Rob Ross ]
 
Chris Graham
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a common mistake I seen made by many of my coworkers (also one I used to make frequently). Strings are objects, and any time you want to compare objects for equality you have to use:
<String>.equals(<String>)
Otherwise, your just comparing the reference of the two objects(i.e. checking to see if the two objects point to the same place in memory [I think that's the right way to word it]).
Only use the == operator to check equality of primatives (i.e. int, long, double, boolean).
--Chris
[ January 12, 2002: Message edited by: Chris Graham ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic