It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes *  Byte == comparision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "*  Byte == comparision" Watch "*  Byte == comparision" New topic

* Byte == comparision

Deepti Dixit

Joined: Dec 27, 2001
Posts: 17

Why does this give 'False' ?
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
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.
[ January 11, 2002: Message edited by: Rob Ross ]

SCJP 1.4
Chris Graham

Joined: Jan 08, 2002
Posts: 22
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:
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).
[ January 12, 2002: Message edited by: Chris Graham ]
I agree. Here's the link:
subject: * Byte == comparision
It's not a secret anymore!