Java programming — Objects and references with methods returning the same instance: class Two { byte x; } class PassO { public static void main(String [] args) { PassO p = new PassO(); p.start(); } void start() { Two t = new Two(); System.out.print(t.x + " "); Two t2 = fix(t); System.out.println(t.x + " " + t2.x); } Two fix(Two tt) { tt.x = 42; return tt; } }

Difficulty: Easy

Correct Answer: 0 42 42

Explanation:


Introduction / Context:
This problem examines Java's pass-by-value of references and default field initialization for primitive types inside objects.



Given Data / Assumptions:

  • Field Two.x is a byte and defaults to 0 in a new object.
  • Method fix mutates the same Two instance and returns that same reference.


Concept / Approach:
Java passes object references by value. Mutating the object via any reference affects the single underlying object instance. Primitives inside objects default to zero if not explicitly set.



Step-by-Step Solution:

Initial print: t.x is 0 by default, so outputs "0 ".Call fix(t): inside fix, tt.x = 42 mutates the same object referenced by t.t2 receives the same reference as t, so both t.x and t2.x are 42 afterwards.Second print: "42 42".


Verification / Alternative check:
Insert an identity check like (t == t2) to confirm both references point to the same object.



Why Other Options Are Wrong:
They assume separate copies or null/default misunderstandings that do not apply here.



Common Pitfalls:
Confusing Java with pass-by-reference semantics; Java always passes by value, but the value of a reference lets you mutate the object.



Final Answer:
0 42 42

More Questions from Operators and Assignments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion