Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals!

 
ashok khetan
Ranch Hand
Posts: 153
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 267
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 464
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeap, toString() returns a new object
so == shallow wont cut it
check the hashcode to verify it
 
marilyn murphy
Ranch Hand
Posts: 84
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic