Loops are used to execute a block of code repeatedly as long as a specified condition is reached. The while loop is the simplest form of iteration in Java.
false. If not, you will create an Infinite Loop, which can crash your application!
The while loop loops through a block of code as long as a specified condition is true. It is often called a "pre-test" loop because the condition is checked before the code block runs.
Essential steps in a while loop:
int i = 0;).i < 5;).i++;).The program enters the loop, checks the condition, executes the body if true, and then jumps back to the top to check the condition again.
The main difference lies in when the condition is evaluated:
Checks condition first. If the condition is false initially, the code never runs.
Executes code first, then checks condition. The code runs at least once even if the condition is false.
Each single execution of the loop body is called one "iteration."
While loops are preferred over for loops in specific scenarios:
| Statement | Action | Result |
|---|---|---|
break |
Terminates the loop immediately. | Jumps to code after the loop. |
continue |
Skips the current iteration. | Jumps back to the condition check. |
Mastering the while loop gives you the power to handle dynamic data where the length is not fixed. It is a fundamental building block of logic in Java.
Next: Learn Java For Loop →