Java Article 11 - For Loops

For and if statements are control structures. They control the flow or logic of your program. For loops allow for a block of code to be looped or executed repeatedly, as many times as desired. This looping is called iteration.

The syntax for a for loop is a bit different and takes getting used to:

for (initial counter value; repeat until this value is false; increment or decrement the counter)
	//block of code to be executed

In more formal programming terms this would be:

for (assignment statement; loop test expression; counting expression)


So here is an actual for loop:

for (int i = 0; i < 10; i++)

Notice the location of the semicolons in the for statement. This is why I say the syntax is a bit different than what you usually see with the semicolon terminating the statement. It can be tough to remember at first but you will get used to it.

So when this line is executed it does the following:

Sets i to 0 with int i = 0;

Checks if i<10 with i < 10;

Prints out i with System.out.println(i);

Inciments i by one with i++. i is now 1

Checks if i<10. This is true so it continues to loop

Prints out i

Inciments i by one with i++. I is now 2.

This continues until i is 10. When i is 10, i < 10 evaluates to false, the loop terminates, and the code within the braces is not executed. If the method the for loop is in is called again it starts the iterative process all over again from the start.

Enter this simple console application and observe the output in the console:

public class SimpleForLoop 
	public static void main(String[] args)
		for (int i = 0; i<10; i++)

The output starts at 0, since i = 0. Then it ends at 9, since the loop terminates when i is 10. Since the loop terminated i is not printed to the console.

Computers do a lot of counting and this is one of the main ways they store, output and manipulate the results of their counting.

So we covered for loop basics. Now I will introduce another concept called concatenation. Concatenation is simply joining one thing to another. This typically applies to joining strings together.

The simplest example would be:

System.out.println("string1" + "string2");

Often you see this used like this:

System.out.println("The answer is: " + someVariable);

Also we will do a bit of type conversion today. Often in programming you have an int and need to covert it to another type such as a string. There are different ways to do this and unfortunately there are a lot of different methods used to do this. This gets confusing since the method you have to use varies widely depending on the situation. There is no trick to knowing which one to use where, you just have to learn them and memorize them over time.

The one we will use today is

int myInt = Integer.parseInt(variableToConvertToAnInt);

Integer is a class and its method, parseInt, will convert a string to an int. For this to work your string has to contain only numbers, not letters or decimals. So variableToConvertToAnInt would have to be something like:

String variableToConvertToAnInt = "11";

Now you get to see this all in action in a Swing app. In the example below we will combine this all together and concatenate some text in a for loop.

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

public class ForLoop extends JFrame implements ActionListener

	int numberFromButton;
	String outputText= "";
	//create our controls
	JLabel labelOne = new JLabel("Clicking the button below will " +
			"control how many time the for loop is run:");
	JLabel labelTwo = new JLabel("Output from the for loop:");
	JButton button1 = new JButton("Run For Loop Once");
	JButton button2 = new JButton("Run For Loop Twice");
	JButton button3 = new JButton("Run For Loop Three Times");
	JButton startButton = new JButton("Run Loop");
	JButton resetButton = new JButton("Reset");
	 // A textPane is a text component that can
	 // display formated characters/paragraphs, images and other
	 // components.
	JTextPane textPane = new JTextPane();
	public ForLoop()
		//container for our controls
		JPanel panel = new JPanel();

		//Add our controls to the panel
		 // A JScrollPane allows our textPane to scroll as its length
		 // increases. Without JScrollPane any new text will disappear
		 // off the bottom of the textPane and will not be visible. 
		JScrollPane scrollPane = new JScrollPane(textPane);
		//This makes the JScrollPane always visible:
		//This set the JScrollPane's size:
		scrollPane.setPreferredSize(new Dimension(200, 200));
		 // We use the default layout manager here. You can 
		 // experiment by uncommenting the statement below to see
		 // the difference.
		//panel.setLayout(new GridLayout(8,1));

	public void actionPerformed(ActionEvent e)
		String cmd = e.getActionCommand();
		if (cmd == "reset")
			//We set our text to "" to clear it.
			outputText = "";
		else //activates if any control is used aside from reset.
			 // This takes the button's ActionCommand,
			 // converts it to a int, then stores this value in
			 // our variable numberFromButton.
			 // See the article for more explanation about this.
			numberFromButton = Integer.parseInt(cmd);
	 // This is called from actionPerformed after clicking one 
	 // of the run buttons.
	public void startTheForLoop()
		 // Here is our for loop. i starts off at 1
		 // and will keep cycling (iterating) while
		 // i<=numberFromButton. Each time it iterates i is increased
		 // by 1.
		for (int i = 1; i<=numberFromButton; i++)
		 // Each time the For loop is cycled though 
		 // (each iteration), i is added to (concatenated)
		 // our variable outputText. We add the +"\n" so each
		 // time i is added, it is added to a new line, and it
		 // looks pretty.
			outputText += i+"\n";
		 // Here I am trying to keep this as simple as possible,
		 // but keep in mind using a StringBuffer is a much more
		 // memory-efficient way to concatenate strings. 
		 // For a simple program like this it does not matter.
		//here we add some text and new lines 
		//to show our for loop ended.
		outputText += "For loop terminated\n\n";
		//Now we set our textPane's text to our string, outputText
	//We talked about the contents of main in article 9
	public static void main(String[] args)
		ForLoop forLoop = new ForLoop();
		forLoop.setSize(500, 400);

One thing to keep in mind when you are working on a real application is that loops that perform a lot of calculations (resource intensive operations) will bog down your program to the point that your user interface will become locked-up or unresponsive.

You can see this by making the following change in our program:

//for (int i = 1; i<=numberFromButton; i++)
for (int i = 1; i<=10000; i++) //This will lock up the EDT/GUI

10000 iterations works for me but you may have to adjust this based on how fast your computer is.

Compile and run this then click on one of the run buttons. Now try to click on another run button. While the for loop is running you should notice the other run buttons don't respond when clicked. This is because the for loop is using up all of your processing power thereby locking-up the event-dispatching thread which is what runs your ActionListener.

This is prevented by multithreading. Threads are an advanced topic so don't worry about them much if you are new, other than to make a mental note to learn more about them some day.

Multithreading is how you keep your UI working while performing calculations or doing other work and is very common in game programming where you have sounds, animation, and highly responsive controls all operating together.

In the next article we will cover another type of loop, the while loop.