Question 291
Consider the following class.
public class Box
{
public int value;
public Box(int v)
{
value = v;
}
}Consider the following code segment.
Box a = new Box(10);
Box b = a;
Box c = new Box(10);
b.value = 20;
System.out.println(a.value + " " + b.value + " " + c.value);What is printed when the code segment executes?
Main Solution
Solution:
Answer: C. The assignment b = a copies the reference, so a and b refer to the same Box object on the heap. A write through b.value is therefore visible through a.value. The third box c was constructed with its own new Box(10) call — it is a distinct object that shares no state with a, even though its initial value happens to equal a's initial value.
Answer: Correct: C
Answer images

