I was given this hypothetical block of code, where although the language used is Java, and Java uses call by value, in this case call by reference had to be used for every method call, and I had to give an output in the format:
y:[result]; y: [result]; y:[result]; x:[result]; a:[result]
public class Main {
static int x = 2;
public static void main(String[] args) {
int[] a = {17, 43, 12};
foo(a[x]);
foo(x);
foo(a[x]);
System.out.println("x:" + x);
System.out.println("a:" + Arrays.toString(a));
}
static void foo(int y) {
x = x - 1;
y = y + 2;
if (x < 0) {
x = 5;
} else if (x > 20) {
x = 7;
}
System.out.println("y:" + y);
}
}.
I'm not 100% sure on how the call by reference works in some cases, and I'm not sure which result is the right one.
Anyway here is one:
foo(a[x]) is called with a[2] (which is 12). y becomes 12 + 2 = 14. x is decremented to 1.
foo(x) is called with x (which is 1). Both x and y point to the value 1 of x. x is decremented to 0 and then x becomes 3 because y=y+2 and y was pointing at the value 1 of x.
foo(a[x]) is called with a[3] (which doesnt exists). x is decremented to 2.
The array a transforms into 17,43,14.
So, the results would be like:
y : 14; y : 3; y : ?; x : 2; a : 17,43,14
I think the thing that confuses me the most is in the case of foo(x). Does y point at variable x or the value of x at the moment the method is called?
foo()is taking in a primitiveintby value, so it is a copy of whatever value you pass in at the call site. There is no reference here.It doesn't matter what
foo()does internally to the value ofy, that value does not get reflected back to the caller.Also, there is no such thing as "point at a value". You can have a pointer/reference to a variable, but not point/refer to a value. A variable holds a value.
This is incorrect. It is
y, notx, that becomes 3.xis still 0 at this point. So the subsequent call tofoo(a[x])is usinga[0]instead, which then decrementsxto -1 and then setsxto 5.