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:
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.