A good answer might be:

NO --- the second for loop is trying to use a variable j that is not defined at that point. (The previous for loop defines a j for its "private" use, only.)

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 )      // No variable "j" can be seen at this point.
        sumOdd  = sumOdd + j;                     

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

Keep things local

Here is another version of the program, which is syntactically correct, but is not nicely done.

class foolishTypist
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;
    int j;         // Same "j" used for both loops.

    for ( 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 ) 
        sumOdd  = sumOdd + j;                     

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

It is best to keep sections of code self-contained. With this (foolish) version, both loops depend on something distant from themselves. Although this program is clear enough, in a much longer program will make the program harder to understand. Here, for instance, is a typical hard to understand program:

class foolishTypist
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;
    int j = 0;
    int i = 1;

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

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

    for ( i = 1;  i < 8; i=i+2 ) 
        sumOdd  = sumOdd + j;                     

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

QUESTION 5:

  1. Will this new program compile?
  2. Will it run?
  3. Will it the two sums be correctly computed?

Click Here after you have answered the question