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
  • 97,651
  • 42
  • 89
  • 110

4 Answers4

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
  • 386,424
  • 207
  • 554
  • 861
3

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

Community
  • 1
  • 1
matt b
  • 135,500
  • 64
  • 278
  • 339
0

Just may be to make it clear, All variables passed by value means that the called method just gets the values of parameters and not a reference (pointer) to these objects, so any modification on these objects in the method body doesn't affect the outer object. Unlike c++ which has the option to pass the object by reference where the method gets the actual object not it's value, so any modification in the method body affects the outer object.Java doesn't have pass by reference.

Feras Odeh
  • 8,854
  • 20
  • 74
  • 119
  • But Java has passes in object references, which makes any modification on these objects in the method body **affect** the outer object. – whiskeysierra Oct 03 '10 at 09:37
-1

In java, variables are passed by value.

fastcodejava
  • 37,849
  • 27
  • 129
  • 182