We'll start with For Loops, one of the most common types of loops. The "For" part of "For Loop" seems to have lost its meaning. But you can think of it like this: "Loop FOR a set number of times." The structure of the For Loop is this: for ( start_value; end_value; increment_number ) {
//YOUR_CODE_HERE
}
While Loops
Another type of loop you can use in Java is called the while loop. While loops are a lot easier to understand than for loops. Here's what they look like: while ( condition ) {
}
So you start with the word "while" in lowercase. The condition you want to test for goes between round brackets. A pair of curly brackets comes next, and the code you want to execute goes between the curly brackets. As an example, here's a while loop that prints out some text (Try the code out for yourself): int loopVal = 0; while ( loopVal < 5) {
System.out.println("Printing Some Text"); loopVal++; }
The condition to test is between the round brackets. We want to keep looping while the variable called loopVal is less than 5. Inside of the curly brackets our code first prints out a line of text. Then we need to increment the loopVal variable. If we don't we'll have an infinite loop, as there is no way for loopVal to get beyond its initial value of 0.
Although we've used a counter (loopVal) to get to the end condition, while loops are best used when you don't really need a counting value, but rather just a checking value. For example, you can keep looping while a key on the keyboard is not pressed. This is common in games programme. The letter "X" can pressed to exit the while loop (called the game loop), and hence the game itself. Another example is looping round a text file while the end of the file has not been reached. Do ... While
Related to the while loop is the do … while loop. It looks like this: int loopVal = 0; do {
System.out.println("Printing Some Text"); loopVal++; } while ( loopVal < 5 );
Again, Java will loop