Loops

What are loops and how do you write them in Java code?

Frequently in a program you have to do something over and over. Java provides some convenient programming statements to let you do just that. They are called loops.

Three Types of Loops

The for Loop
In this type of loop you create a loop counter variable and initialize it to a starting value, you provide a test to determine when the loop is finished, and you provide a way of changing the value of the loop counter (either incrementing or decrementing). Everything that you want to do over and over is placed inside of braces.



The while Loop
In this type of loop you create a loop counter variable and initialize it before the loops is set up. The while line in the loop just contains the "test" conditional statement. As long as this statement is true the loop will continue. Something done inside the loop must eventually change the loop counter so that the conditional is false.



The do-while Loop
In this type of loop you create a loop counter variable and initialize it before the loops is set up just as you do in the while loop. The main difference is that in the do...while loop the conditional is not checked till the end of the loop where as in the while loop it is checked at the beginning. That means that if a while loop's conditional is false to start with it will not execute at all. But, a do...while loop will always execute at least once because even if its' loop counter is false to start with that will not be checked till the end of the loop.