The moose likes Mock Exam Errata and the fly likes Majii's Exam..Paper1 #6 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Mock Exam Errata
Reply Bookmark "Majii Watch "Majii New topic
Author

Majii's Exam..Paper1 #6

Cheryl Gray
Ranch Hand

Joined: Nov 17, 2000
Posts: 44
I'm confused by #6 Paper1 vs. #20 Paper2;
Double a = new Double(Double.NaN);
Double b = new Double(Double.Nan);
if (a.equals(b))
System.out.prinln("true");
else //here the answer is TRUE
System.out.println("false");
HOWEVER..I left out unnecessary lines
//Paper 2 #20
MyClass(int maxElements)
{ this.maxElements = maxElements;}
//in main
MyClass a = new MyClass(100);
MyClass b = new MyClass(100);
if (a.equals(b))
.....print true //here the answer is FALSE
else
print false
Why is this? Any help would be appreciated.


Anything is possible to those who believe.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
The equals method is defined in the Object class, so it is included in all classes. It is defined in the Object Class as Object obj2.equals(Object obj1) will be true if and only if obj1 is the same object as obj2. This is the minimum requirement for the equals method.
However, classes override the equals method to give it a better meaning for thier class. For Double, equals is overridden so it will return true if the value of the doubles are == to each other with the exception of NAN where == will be false, but equals will return true.
So for the above question, Double.NaN.equals(Double.NaN) will return true as per the overridden method in Double. But for MyClass, if they don't override equals then it is going to return false unless the objects refer to the same objec, which in the case above they don't.
Hope that makes sense.
Bill
Cheryl Gray
Ranch Hand

Joined: Nov 17, 2000
Posts: 44
Bill:
Thanks for the explanation. I now remember reading a little about the overriding part in Bruce Eckel's book.
 
 
subject: Majii's Exam..Paper1 #6
 
Threads others viewed
Q'tion from Majji's paper
== Vs equals()
hii
loops
about == equals
MyEclipse, The Clear Choice

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture