1. While Loops, Do-While Loops
The While Loop
A loop allows you to run the same lines of code over and over. Usually, loops also have a condition, which must be true for the loop to run. When the condition becomes false, a loop stops running. Take a look at this first while loop:
public class MyProgram { public static void main(String[] args) { int i = 0; //We often use the name i, which stands for "iterator" or "index" while(i < 10) { //Does not run when i is greater or equal to 10 System.out.println(i); i++; //remember this is pretty much the same as i = i + 1, adding 1 to i } } }
A while loop always has the following syntax: while(CONDITION) { STATEMENTS }
. If the condition is always true, we call the loop an infinite loop
The loop above starts with i equal to zero. Because i is less than ten, the loop begins. If you started i with 10, the loop would not even run once, since the while loop checks the condition prior to beginning. Once we enter the loop, it prints i, and then it adds one to i. After that, it jumps back to the top of the loop, checking if i is still less than 10. The result is a program that outputs the numbers 0 through 9.
While loop variable declaration
The variables used in the condition of while loops always need to be declare before the beginning of a while loop. This is because variables declared in the curly brackets are reset every time it re-enters the loop:
public class MyProgram { public static void main(String[] args) { int ab = 0; while(ab < 10) { int cd = 42; //cd is defined here, and is redefined each time the loop runs System.out.println(ab + cd); cd = cd + 5; //this line doesn't change the program ab++; } //cd ceases to exist here even when the loop restarts } }
The do-while loop
A do while loop behaves almost exactly the same as a while loop, except the condition is checked at the bottom of the loop. In other words, even if the condition is false, the loop will execute at least once:
public class MyProgram { public static void main(String[] args) { int x = 9999; do { System.out.println(x); //This outputs 9999 x++; }while( x < 10 ); //This is false, so the loop ends } }
While loops are especially useful when getting user input. It allows you to run code before the user enters input, and repeat the code if the user inputs certain information.