Iterations
Four Different Loops In Java
Often times, we want to continuously execute a certain block of code without accordingly to a dynamic number of iterations. For this reason, Java provides us with a mechanism called loops. Loops are two-part:
- Condition -
A condition statement returns a boolean value; that is, it returns either true or false. If and only if the condition is true, Java will execute the statements contained in the body. The condition is checked before each iteration of the loop. - Body -
The body contains any statements that should be executed if the condition is met. If the body consists of multiple statements that must be executed, then these statements must be grouped together to form a block statement by enclosing them in braces { }.
Different Circumstances Require Different Kinds Of Loops
For this reason, Java provides us with four different kinds of loops. Each type of loop is specific to its purpose. The most difficult part is not remember which loop is which, but rather which loop should be used during which circumstance. This, unfortunately, cannot be taught. It must be learned through experience. I encourage you to try each loop and get a feel for when the use of that loop would be appropriate.
While Loop
Loops Controlled By A Condition
A while loop executes a block of code continuously in a repeated fashion while the specified condition returns true. While loops are often used to repeatedly increment values or perform tasks. What makes this loop differnet from all the rest is that the test condition must be true BEFORE each repetition.
The basic structure of a while loop follows:
while (condition)
{
statement
}
Let us examine a sample while loop.
int myNumber = 1;
while (myNumber <= 10)
{
System.out.println(myNumber);
myNumber++;
}
int myNumber = 1;
We declare and initialize anintwith an initial value of 1.while(myNumber <= 10)The condition we provide tells Java to run this loop as long as myNumber is less than or equal to 10.
System.out.println(myNumber);
Java will print out the value ofmyNumberat each iteration.myNumber++;
Increment the variablemyNumberby 1.
When Java reaches the end of the block, it loops around to the beginning. It checks to make sure the condition is still valid, and then continues through the block again.
The code above should print out something like this in the console window.
1
2
3
45
6
7
8
9
10
Do…While Loop
Do First, Then Decide
A do...while loop executes a block of code continuously in a repeated fashion while the specified condition returns true. This loop differs from the while loop in that it enters and completes the first iteration without checking the condition. The do...while loop is often used to compound numerical data.
The basic structure of a do...while loop follows:
do
{
statement}
while (condition);
Please Note: Unlike the while loop, the do...while loop uses the do keyword to enter the loop. Also, notice how a semicolon follows the while (condition) and the statement is placed afer the body of the loop.
Let us examine a sample do...while loop.
int myNumber = 1;
do
{
System.out.println(myNumber);myNumber++;
}
while (myNumber <= 10);
The looping mechanism works very similarly to that of the while loop. Please see above for detailed description.
The code above should print out something like this in the console window.
1
2
3
4
56
7
8
9
10
For Loop
A for loop executes a block of code continuously in a repeated fashion with a counter keeping track of how many iterations have passed. The condition of a for statement is the upper/lower bounds for the counter. Rather than expecting a boolean value from the variables it works with, a for loop’s condition is that it is running between the bounds of the counter.
The basic structure of a for loop follows:
for (int i = 0; i <= n; i++)
{
statement}
Let us examine a sample for loop.
for (int myNumber = 1; myNumber <= 10; myNumber++)
{System.out.println(myNumber);
}
The condition for a for loop consists of three pieces:
int myNumber = 1;This is the initializer. It initializes the counter variable to its initial value.
myNumber <= 10;
This is synonymous with thewhilecondition. It represents how long to continue the loop.myNumber++;
It is here that the final piece of code is executed before the end of each iteration. This tells Java to increment the counter.
The code above should print out something like this in the console window.
1
2
3
4
56
7
8
9
10
For Each
Because It’s So Much Easier With ArrayLists
A For Each loop is a new type of loop that is only included with the most recent copies of Java (5.0 and higher). This loop is significant because it does not keep a counter or a test condition. Rather, it takes a data structure known as ArrayLists, which we will cover in a later section, and iterates through each entry in the ArrayList, executing the body’s statements for each of the entries.
The basic structure of a For Each loop follows:
for (Object o : someArrayList)
{
statement}
Please Note: Though this loop does share the same keyword for with the for loop, it behaves very differently.
Let us examine a sample For Each loop.
// Let us assume that myList contains a list of int objects 1 through 10
ArrayList myList = listOfNumbersOneThroughTen;
for(int myNumber : myList)
{
System.out.println(myNumber);
}
The code above should print out something like this in the console window.
1
2
3
45
6
7
8
9
10
Common Errors
Oops! I forgot the semicolon! Boom!
In any programming language it is very easy to make mistakes. We can often lower our tendency to make mistakes by writing clear and understandable code. It is also very important to write comments in the code to organize your statements. When it comes to loops, this is even more critical than ever before. Loops have a dangerous possibility of running forever without end if even the simplest error is made.
Infinite Loops
Infinite loops arise when the stop condition cannot and will not ever be met. This can be cause by almost and unlimited amount of factors. The most common factor is when the programmer forgets to increment the counter after each execution. Errors like these can cause the program to run into a loop that runs infinitely. When we say infinitely, we mean that it will continue until either the program has used up all of the system’s resources and cannot continue any further or when the user pulls the plug.
Here are some cases where the program might run into an infinite loop. As an exercise, try to rewrite the loop such that the problem is solved.
int i = 0;
while ( i <= 10)
{System.out.println(i);
}
for (int i = 0; i <= 10; i++)
{
System.out.println(i);i–;
}
int i;
do
{i = 0;
System.out.println(i);
i++;
}
while(i <= 10);