I’m having some trouble understanding pretty basic Java code, I can’t figure out how in the end of compiling x=2. Because through my logic it should be 4. The code itself:
public class eksami_harjutused {
public static int x=2;
public static int y=2;
public static void main(String[] args) {
foo(bar(foo(x)));
System.out.println("main x,y: "+x+" "+y);
}
public static int foo(int x) {
x++;
y++;
System.out.println("foo x,y: "+x+" "+y);
return x;
}
public static int bar(int x) {
int z=0, y=10, u=0;
--y;
for(y=1; y<(x*x); y++) {
for(z=1; z<x; z++) {
u++;
}
}
System.out.println("bar x,y: "+x+" "+y);
return z;
}
}
It prints out:
foo x,y: 3 3
bar x,y: 3 9
foo x,y: 4 4
main x,y: 2 4
Well,
xis passed by value – since it isinttype, so any modification toxin the callee functions will not affectxin the caller function. You can think of giving a copy of value inxto the callee, and the callee can do whatever with it without affecting thexin the scope of the caller.Passing by value is done for all the primitive types in Java. And passing by reference is done for the rest (Object – note that array is Object).
Another thing is the effect of variable shadowing in
fooandbarmethods:xis declared as parameter tofooandbar, so the class memberxis shadowed. Any access toxinfooandbarmethods will refer to the argument passed in, not the class memberx.The value of
xprinted in themainmethod is from the class memberx, which is never touched during the execution of the program.In contrast, you can see the variable
ymodified twice in 2 calls to thefoomethod, sinceyinfoomethod will refer to the class membery. Theyinbarmethod, however, refer to the local variableydeclared in thebarmethod.