简体   繁体   中英

Can someone please explain why the answer is 6?

private int field;

public void f(int n) {
    n = n + field;
    field = field + n;
    n = n + 2; 
}

public void g() {
    field = 2;
    f(field); 
}

What would be the final value of field after invoking g() ? I know the answer is 6 but could someone please explain why?

you can expand your code to something like this:

field = 2;         //               field == 2
int n = field;     // n == 2;       field == 2
n = n + field;     // n = 2+2 == 4; field == 2
field = field + n; // n == 4;       field = 2+4 == 6
n = n + 2;         // n = 4+2 == 6; field == 6

final values:

field == 6
n == 6

NOTE: a = b means that only value of b stored/copied into a , but a and b are two different variables which are not related to each other

@Lashane has give you an answer but I try to explain it as simple as I can. In method g() you:

  1. set variable ' field ' as 2.
  2. Then call method f . Note that the ' field ' is a class variable and a parameter of method f(int n) . So at start of method f both variables 'n' and 'field' are set as 2.

Then the calculations (included in method f ) are clear:

 n = n + field; // n = 2 + 2 == 4
 field = field + n; // field = 2 + 4
 n = n + 2; // n = 4 + 2 == 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM