A. true true
B. false true
C. true false
D. false false
E. Compilation fails
F. An exception is thrown at runtime
✓ A is correct. The references f1, z, and f3 all refer to the same instance of Fizz. The final
modifier assures that a reference variable cannot be referred to a different object, but final
doesn’t keep the object’s state from changing.
B, C, D, E, and F are incorrect based on the above.
I don't have any clue how you get "false false" as output on your machine. The answer is "true true", f1 and f3 do indeed point to the same object. Read this tutorial for more info on calling methods with objects...
I have run the program over my machine and it is giving me true true, that is answer A, which is basically correct.
How come you are getting false false? The flow of the program is like this
1- First the first final object is created which is f1 and having value of x as 5.
2- Second a non-final instance is created called f2 and having value of x as 5.
3- On the third step, a method call to fizzSwitch() is made in which instances f1 and f2 are passed and their return instance has to be assigned to instance three which is f3.
4- If you see the method signature
It has two parameters that are instances x and y.
5- When the method call is made to fizzSwitch, this state is made
x and f1 referrring to instance 1
y and f2 referring to instance 2
Inside the method, first line, the final reference z also starts pointing towards instance 1. I
6- It changes the state of object 1 and now instead of 5 x is having the value 6.
7- Remember that, the state of final objects can be changed and that is what happened to object 1.
8- Then the reference is returned and the method call completes and at this point reference f3 is also referring towards object of fizztest.
When this statement is encountered
Basically the equals method checks whether two references are referring to the same object or not. Remember object class equals method using = operator to check for equality
unless and until you override the implementation. In this case case both are referring to the same object, so first condition answer is true.
When you say
So both references are referring to the same object and the answer will be true as the value of x is 6.