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 );
  } 
}