• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals( ) method

 
kiran goud
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer i = new Integer(42);
Long l = new Long(42);
Double d = new Double(42.0);

Which of the following are true ( Select two answers)

a)(i==l)
b)(i==d)
c)(d==l)
d)i.equals(d)
e)d.equals(i)
f)i.equals(42)

Please give the inputs !!
 
Anil Hulikal
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the compilation point of view, first three are "incomparable", and the last equals call has int as the parameter when it requires an (Object obj).

So, options 4 and 5 are true, from the compilation perspective.

Regards,
Anil
 
Wladimir Babitzki
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's doubtful about d and e are true.

The equals methods of all wrapper class check not only the primitive representation, but also that the checked object is of the same wrapper class (in our case Integer and Double) as well.
 
Anil Hulikal
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, as I emphasized, they are true from compilation perspective: In other words, they don't give compilation errors. This does not mean that run time results would be boolean "true".

Please try compiling and running the following code as-is, and then try again with "//" removed for the print statements one at a time.


The following specs from the sections 15.21.3 and 5.5 of JLS may be pertinent here

|
A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (�5.5).
|



|
The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:
If S is a class type:
If T is a class type, then S and T must be related classes-that is, S and T must be the same class, or S a subclass of T, or T a subclass of S; otherwise a compile-time error occurs.
|



Regards,
Anil
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic