Senior
// 3 public class Variables { public static void main(String[] args) { A a = new A(); a.val = 1; inc(a); System.out.println(a.val); set(a); System.out.println(a.val); } public static class A { public int val; } public static void inc(A a) { a.val++; } public static void set(A a) { a = new A(); a.val = 10; } }
sobes.tech AI
Answer from AI
This code does the following:
- Creates an object
A a = new A();with a fieldval. - Sets
a.valto 1. - Calls the method
inc(a), which increasesa.valby 1. Nowa.valequals 2. - Prints
a.val— the output will be2. - Calls the method
set(a), in which the parameterais locally reassigned to a new objectnew A()withval = 10. However, this does not affect the object outside the method because the parameter is passed by value of the reference, but the reference itself is copied. - Prints
a.val— the output will still be2.
Final output:
2
2
Explanation:
- In Java, objects are passed to methods by value of the reference. That is, a copy of the reference to the object is passed.
- In the
incmethod, the field of the object thatarefers to is modified, so the changes are visible outside the method. - In the
setmethod, the referenceais reassigned to a new object, but this is a local change to the reference and does not affect the original object outside the method.