File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Equals and ==

 
hewitt charlotte
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 282
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just copied your code and ran it, I got true and true.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure your "o1 = o2" assignment wasn't between the println statements when you got that output?
 
hewitt charlotte
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
hewitt charlotte
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 320
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic