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
posted
0
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
posted
0
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: 83
posted
0
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.