1

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

Devoted
  • 177,705
  • 43
  • 90
  • 110

3 Answers3

6

The variable a is a copy of the reference being passed in, so it still has the same value and refers to the same Account object as the account variable (that is, until you reassign a). 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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
3

It might be time for you to read more about pass-by-value in Java.

Community
  • 1
  • 1
matt b
  • 138,234
  • 66
  • 282
  • 345
-2

In java, variables are passed by value.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186