In the following program why the output is of else statement ie. "Objects have different values" 1: class MyClass 2: { 3: static int maxElements; 4: 5: MyClass(int maxElements) 6: { 7: this.maxElements = maxElements; 8: } 9: 10: } 11: 12: public class Q19 13: { 14: public static void main(String[] args) 15: { 16: 17: MyClass a = new MyClass(100); 18: MyClass b = new MyClass(100); 19: 20: if(a.equals(b)) 21: System.out.println("Objects have the same values"); 22: else 23: System.out.println("Objects have different values"); 24: } 25: } A) Compilation error at line 20. equals() method was not defined. B) Compiles fine, runtime exception at line 20. C) Prints "Objects have the same values". D) Prints "Objects have different values". Correct awr is D HIHI
leena rane
Ranch Hand
Joined: Aug 13, 2001
Posts: 280
posted
0
Since Myclass class does not hav any equals method, the equals method of Object is used.This only check whether the two objects have the same reference.This is only possible if it's the same object.Since you hav used new to create 2 objects naturally 2 objects are created.So it returns false. HIH
Nisheeth Kaushal
Ranch Hand
Joined: Jul 20, 2001
Posts: 87
posted
0
Thanx Leena Please solve my one more prob - 1: public void check() 2: { 3: System.out.println(Math.min(-0.0,+0.0)); 4: System.out.println(Math.max(-0.0,+0.0)); 5: System.out.println(Math.min(-0.0,+0.0) == Math.max(0.0,+0.0)); 6: }
The order of floating/double values is -Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 --> Positive Numbers/Fractions --> Infinity then why the fifth line returns true. this means -0.0 and 0.0 are equal. Please reply urgently. Nisheeth. HIHI
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Nisheeth, I had written a small program to understand the "equals and == " bit...see if it helps...
The output is:
The lowdown on equals and == is that if it is used by any class that does not override it...it impartially returns false. Also, it is a compile time error if one of the operands cannot be cast into the other's type. Some of the classes that overrides the equals() method are BitSet, Date, File and the Wrapper Classes. Hope this helps Shyam
[This message has been edited by Shyamsundar Gururaj (edited October 29, 2001).]
Nisheeth Kaushal
Ranch Hand
Joined: Jul 20, 2001
Posts: 87
posted
0
Thanx Gururaj, Your program is sufficient enough to understand equals() and ==. And will u please explain me that then how can we test for the equality of two objects and their object references. Please reply fast. Nisheeth. Thanx in advance. HIHI.
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Nisheeth, If your class needs to use equals(), it must override the method defined in the object class. For more information, Visit