98.4k views
1 vote
Consider the following class definition:

public class Widget {
private int value;
public Widget(int val) {
value = val;
}
public int get() {
return value;
}
public void set(int n) {
value = n;
}
}
After the following client code executes:
Widget w1 = new Widget (5);
widget w2 = w1;
w2.set(1);
what is the value of the following expression?
w1.get()
a. 1
b. 0
c. 5
d. w1 is no longer valid

1 Answer

7 votes

Final answer:

The value of the expression w1.get() after the code executes is 1.

Step-by-step explanation:

The value of the expression w1.get() after the code executes is 1.

When the code w2.set(1) is executed, it modifies the value of w2, which is a reference to the same Widget object as w1. Therefore, when we call w1.get(), it returns the updated value, which is 1.

In Java, objects are passed by reference, so even though w1 and w2 are different references, they are pointing to the same object in memory.

User Confiance
by
8.9k points