Keep things local

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:

No. The second for loop is trying to use a variable j that is not defined at that point. (The first for statement declares a j than can only be seen within that loop.)

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 )    //  "j" can not 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, a longer program might be 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. Is it correct?