Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1104 :

Posted: Thu Dec 28, 2017 2:52 pm
by Kevin30
The question is:
Consider the following lines of code:

Integer i = new Integer(42);
Long ln = new Long(42);
Double d = new Double(42.0);

Which of the following options are valid code fragments?
i == ln;
ln == d;
i.equals(d);
d.equals(ln);
ln.equals(42);
The answer is that the following are correct:
i.equals(d);
d.equals(ln);
ln.equals(42);

I wonder why "i.equals(d);" is correct?
i == d
can never happen because i and d are references to different classes of objects that have no relation between themselves.
But...I think the answer is correct because equals() can be overridden.

The same thing goes for "d.equals(ln)" I think.

Am I correct?

Re: About Question enthuware.ocajp.i.v7.2.1104 :

Posted: Thu Dec 28, 2017 3:49 pm
by admin
i.equals(d) compiles fine because the equals method is defined in Object class and its parameter type is Object ( public void equals(Object obj). So any class that overrides equals method also must have the parameter type i.e. Object.

For this reason, you can actually pass any object as an argument to the equals method. Of course, at run time, whether it returns true or false depends on how the equals method is coded. In this case, i.equals(d) will return false.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.1104 :

Posted: Fri Dec 11, 2020 5:40 pm
by jeff_kola
Is there a list of these statements that can never happen in the JLS? Is it the same section as the unreachable code?

Re: About Question enthuware.ocajp.i.v7.2.1104 :

Posted: Sat Dec 12, 2020 9:21 pm
by admin
I am sorry, there is no such list as such but there are only a few things that you need to remember for the exam-
1. unreachable code
2. Invalid reference assignment
3. Invalid primitive assignments

There are, of course, several rules related to various topics which you will learn while studying those topics. For example, exceptions, loops, conditionals. Any violation of those rules will cause compilation error.