tgoop.com/topJavaQuizExplain/266
Last Update:
What will be the output of the code?
❌ A. 10
✅ B. 20
❌ C. 30
❌ D. Compilation error
❌ E. Runtime error
❌ F. None of the above
Explanation:
The code defines a class MyClass with a private instance variable myVar, a constructor that initializes myVar, and getter and setter methods for myVar.
In the Main class, an object obj1 of MyClass is created with the value 10 passed as an argument to the constructor. Then, obj2 is assigned a reference to the same object as obj1. Next, the setMyVar() method is called on obj2 with a value of 20. Finally, the value of myVar in obj1 is printed.
Since obj1 and obj2 refer to the same object, calling setMyVar() on obj2 also changes the value of myVar in obj1. Therefore, the output will be 20.
Therefore, the correct answer is option 20.
BY Explanations “Top Java Quiz Questions”
Share with your friend now:
tgoop.com/topJavaQuizExplain/266