go to previous page   go to home page   go to next page

Can the same identifier be used as an name for a local variable in two different methods?

Answer:

Yes — the scopes will not overlap so there will be two local variables, one per method, each with the same name.


Instance Variable and Local Variable
with Same Name

Although it is usually a bad idea, you can declare a formal parameter or a local variable with the same name as one of the instance variables.


class CheckingAccount
{
  . . . .
  private int balance;

  . . . .
  public void processDeposit( int amount )
  {
    int balance = 0;                // New declaration of balance.
    balance = balance + amount ;    // This uses the local variable, balance.
  }

}

This is not a syntax error (although it will probably result in a logic error, a bug). The compiler will compile this code without complaint. The second declaration of balance (the one in red) creates a local variable for the processDeposit method. The scope of this variable starts with its declaration and ends at the end of the block (as with all local variables). So the next statement uses the local variable, not the instance variable.

When this modified method is called, it will add amount to the local variable balance, and then return to the caller. The local variable will no longer hold a value after the method has returned. The instance variable will not have been changed.

Hint:   Think of statements as looking "upward" from their own location to find each of their variables. They can look outside of their "glass box" in any direction if they fail to find a variable inside their own method.

It is almost always a mistake to use the same name for an instance variable and for a local variable. But it is not a syntax error, so the compiler will not warn you of impending doom.


QUESTION 11:

Examine this modification:

class CheckingAccount
{
  . . . .
  private int balance;

  . . . .
  public void processDeposit( int amount )
  {
    int balance = 0;                     // New declaration of balance.
    this.balance = balance + amount ;    // ??????
  }

}

Does the method change the instance variable balance ?