Moving Statements Outside the Loop

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.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.

Answer:

Yes, these two statements:

int diameter = width/10;
int Y = height/2 - diameter/2;    // the top edge of the squares

keep computing the same thing over and over.

Moving Statements Outside the Loop

There is no need to compute diameter for each iteration of the loop. The same for Y, the top edge of the squares. It is always the same. These two statments can be moved outside of the loop, as in the following version of the applet.

import javax.swing.JApplet;
import java.awt.*;

// Assume that the drawing area is 300 by 150.
// Draw ten red circles side-by-side across the drawing area.
public class TenCircles extends JApplet
{
  final int width = 300, height = 150;

  public void paint ( Graphics gr )
  { 
    gr.setColor( Color.red );
    int diameter = width/10;
    int Y = height/2 - diameter/2;    // the top edge of the squares

    int count =  0 ;
    while (  count < 10  )
    {
      int X = count*diameter;           // the left edge of each square
      gr.drawOval( X, Y, diameter, diameter );
      count = count + 1; 
    }

  }
}

This version is somewhat better than the previous version because needless computations are avoided. If a loop body is iterated millions of times (not unusual in a large programs) the program will run faster if some statements can be moved outside the loop.

QUESTION 15:

In the above program what is the effect of changing the statement

int diameter =  (width/10);

to

int diameter =  20;