Can't use the Same Name in the Same Scope

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Is the scope of a local variable always the entire body of a method?

Answer:

No — the scope starts where the variable was declared and continues to the end of its block. Sometimes a local variable is declared in the middle of a block, close to the statement which first uses it.

Can't use the Same Name in the Same Scope

It is a mistake to use the same identifier twice in the same scope. For example, the following is a mistake:

class CheckingAccount
{
  . . . .
  private int    balance;

  public void processCheck( int  amount )
  {                          
    int amount;    

    incrementUse();
    if ( balance < 100000 )
      amount = 15;                    // which amount ??? 
    else
      amount = 0;                     // which amount ??? 

    balance =  balance -  amount ;    // which amount ??? 
  } 
}

The scope of the formal parameter amount overlaps the scope of the local variable (also named amount), so this is a mistake. This is a different situation than a previous example where two methods used the same name for their formal parameters. In that situation the scopes did not overlap and there was no confusion.

QUESTION 10:

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