0

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!

njfy410
  • 139
  • 12

2 Answers2

1

Q1 : where the last q is coming from?

It is the static int q that you updated in the method m1() it is incremented to 5.

Q2 : why c.p printed 6 in m2()? and q as 2?

Your parameter name is the culprit. The q = q + 3, p = q + 1 refers to parameter value instead of static variable q. Only local variable gets updated, the static variable q stays at 2 , which you have assigned before calling m2

Try changing the name of parameter name q to r in the method m2() and see for yourself.

SomeDude
  • 13,876
  • 5
  • 21
  • 44
0

While you referencing p variable in:

private int m2(int q) { 
       // Note that q now shadowing static variable q of C2
       p= q+1; // Same as to call C2.p = q + 1
       q= q+3; // Here you addressing m2 input variable and not the static field q
       return q; 
}

you actually referencing referencing static variable of the class C2. Therefore it nullify the fact you doing reset to 1 before the call:

  q = 2; // Actually similar to calling C2.q = 2, instead
  c.p= 1; // While pointing static variables you can simply do C2.p

Now it's quite similar with m1 method:

private int m1(int p) { 
     // Now static p shadowed by method input parameter
     p= q+1; // Changing p of method input parameter
     q= q+3; // Same as C2.q += 3
     return q; 
}

Now you'd probably need to consider read following material to have better picture of how things suppose to work:

  1. Understanding Class Members
  2. Shadowed Classes or Variables in Java
  3. What is variable shadowing used for in a Java class?
Artem Barger
  • 40,769
  • 9
  • 59
  • 81