I thought I understood variable scope until I came across this bit of code:
private static void someMethod(int i, Account a) {
i++;
a.deposit(5);
a = new Account(80);
}
int score = 10;
Account account = new Account(100);
someMethod(score, account);
System.out.println(score); // prints 10
System.out.println(account.balance); // prints 105!!!
EDIT: I understand why a=new Account(80) would not do anything but I’m confused about a.deposit(5) actually working since a is just a copy of the original Account being passed in…
The variable
ais a copy of the reference being passed in, so it still has the same value and refers to the sameAccountobject as theaccountvariable (that is, until you reassigna). When you make the deposit, you’re still working with a reference to the original object that is still referred to in the outer scope.