java - 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 final value of field after invoking g()? know answer 6 please explain why?

you can expand code 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 value of b stored/copied a, a , b 2 different variables not related each other


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -