aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals!" Watch "equals!" New topic
Author

equals!

ashok khetan
Ranch Hand

Joined: Jul 29, 2001
Posts: 153
hi! can u pl explain the output of this code? i think in stat 1 internally the toString() method is called so there shouldn't be any difference between 1 & 2.
thanx.
ashok.
____________
class MyClass {
public static void main(String args[ ]) {
Integer i = new Integer(10);
System.out.println(i == i); //1--> true
System.out.println(i.toString() == i.toString());//2--> false
}
}
____________
Roopa Bagur
Ranch Hand

Joined: Nov 03, 2000
Posts: 267
My understanding is toString method returns a new string object.Since == checks the reference of the objects .== would fail comparing to different string objects.
Anybody correct me if I am wrong.
Originally posted by ashok khetan:
hi! can u pl explain the output of this code? i think in stat 1 internally the toString() method is called so there shouldn't be any difference between 1 & 2.
thanx.
ashok.
____________
class MyClass {
public static void main(String args[ ]) {
Integer i = new Integer(10);
System.out.println(i == i); //1--> true
System.out.println(i.toString() == i.toString());//2--> false
}
}
____________

Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Yeap, toString() returns a new object
so == shallow wont cut it
check the hashcode to verify it
marilyn murphy
Ranch Hand

Joined: Aug 28, 2001
Posts: 84
Originally posted by ashok khetan:
i == i is done first (i.e. 10 == 10 ) = true.
Then the result (i.e. "true") is changed to a String by the implicit toString().
You know that if you use ( i.toString() ).equals( i.toString() ) you will get "true" for the result.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: equals!