| Author |
Equals and ==
|
hewitt charlotte
Greenhorn
Joined: Jul 08, 2007
Posts: 5
|
|
The base implementation of equals method in the Object class checks for reference equality. class equals { public static void main(String args[]) { Object o1= new Object(); Object o2 = new Object(); o1=o2; System.out.println(o1==o2);; System.out.println(o1.equals(o2));; } } Then why the result is : false and true .
|
 |
James Hambrick
Ranch Hand
Joined: Sep 04, 2004
Posts: 277
|
|
|
I just copied your code and ran it, I got true and true.
|
Visit my blog! http://jameshambrick.com
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Are you sure your "o1 = o2" assignment wasn't between the println statements when you got that output?
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
hewitt charlotte
Greenhorn
Joined: Jul 08, 2007
Posts: 5
|
|
|
 |
hewitt charlotte
Greenhorn
Joined: Jul 08, 2007
Posts: 5
|
|
class equals { public static void main(String args[]) { Object o1= new Object(); Object o2 = new Object(); o1=o2; System.out.println("== Magic " +o1==o2);; System.out.println("== Magic " +o1.equals(o2));; } } C:\mridul>javac equals.java C:\mridul>java equals false == Magic true C:\mridul> Please help , why its coming wrong for me.
|
 |
Bob Ruth
Ranch Hand
Joined: Jun 04, 2007
Posts: 318
|
|
System.out.println("== Magic " +o1==o2);; This is merely a guess.... I have read something about the concatenationf of strings with the variables following them... and I wonder if precedence is getting int he way here. If this string is being interpreted as "== Magic " + o1 (and the 01 is getting converted to string and concatenated to the "== Magic " string and THEN the == comparison is running against Object o2 and of course it will not equal! What made me suspicious is that the "== Magic " string doesnt even show up in the console output. Try this instead.... just as a test.... System.out.println("== Magic " + (o1==o2));; notice the extra parens around o1==o2.... give it a shot...
|
------------------------
Bob
SCJP - 86% - June 11, 2009
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by hewitt charlotte: ...why its coming wrong for me.
That's an entirely different situation, which was answered when you posted the same question last weekend.
|
 |
 |
|
|
subject: Equals and ==
|
|
|