Same Name used in Several Loops

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

Answer:

Yes — the several uses of j are all within the for statement and its loop body.

Same Name used in Several Loops

Other for statements might use the same identifier (the same name) in declaring their loop control variable, but each of these is a different variable which can be seen only by its own loop. Here is an example:

class SameName
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;

    for ( int j = 0;  j < 8; j=j+2 )      // a variable named "j"
        sumEven = sumEven + j;
    System.out.println( "The sum of evens is: " + sumEven ); 

    for ( int j = 1;  j < 8; j=j+2 )      // a different variable named "j"
        sumOdd  = sumOdd + j;
    System.out.println( "The sum of odds is: " + sumOdd );
  } 
}

The two loops work correctly, and don't interfere with each other, even though each one has its own variable named j.

QUESTION 4:

Is the following code correct?


class SameName
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;

    for ( int j = 0;  j < 8; j=j+2 )
        sumEven = sumEven + j;

    System.out.println( "The sum of evens is: " + sumEven ); 

    for ( j = 1;  j < 8; j=j+2 )      // Notice the change in this line
        sumOdd  = sumOdd + j;                     

    System.out.println( "The sum of odds is: " + sumOdd );
  } 
}