I came across this problem doing some practice sets and was a bit confused about parts of it. The answer to what for the two print statements are (5,1,5) and (8,6,2)
public class C2 {
private int p= 1;
private static int q= 2;
private int m1(int p) { p= q+1; q= q+3; return q; }
private int m2(int q) { p= q+1; q= q+3; return q; }
public static void main() {
C2 c= new C2();
int x= c.m1(5);
System.out.println(x + ", " + c.p + ", " + q);
q= 2; c.p= 1;
x= c.m2(5);
System.out.println(x + ", " + c.p + ", " + q);
}
}
It seems in the first print statement answer, the static int q is used and passed through the method and returns 5 which makes sense, and that the other field p is used for c.p. I'm a bit confused where the last q is coming from? Is it the same q that I returned to set equal to the variable x?
For the second print statement answer, I understand where the 8 comes from, however, why is c.p = 6 when it is stated as being c.p = 1 right above? Did we overwrite this variable during the method call, and if we did, why did c.p not change when executing the first println statement, instead staying at 1? Finally, the q in this case, why is it not like the first println statement where it seems q is the same q given by the return statement? Sorry for the boatload of questions!