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

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

-2

In java, variables are passed by value.

2 Comments

I think you should remove this, since objects are passed by reference.
@stacker - how can that be? Just the answer before says it is pass by value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.