Java While Loop
Loops
Loops can execute a block of code as long as a specified
condition is true.
Loops are handy because they save time, reduce errors, and
they make code more readable.
Java While Loop
The while loop repeats a block of code as long as the specified
condition is true:
Syntax
while (condition) {
// code block to be executed
In the example below, the code in the loop will run again and
again, as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
[Link](i);
i++;
Note: Do not forget to increase the variable used in the
condition (i++), otherwise the loop will never end!
Do you wonder why we used the letter i in the example above?
It's a counter variable and a common choice in simple loops
because it's short, traditional, and stands for 'index' or
'iterator'.
Countdown Example
You can also use a while loop to count down. This example
counts from 3 to 1, and then prints "Happy New Year!!" at the
end:
Example
int countdown = 3;
while (countdown > 0) {
[Link](countdown);
countdown--;
[Link]("Happy New Year!!");
While Loop With False Condition
In the previous examples, the condition was true at the start,
so the loop ran one or more times. But if the condition
is false at the beginning, the code inside the loop will never
run:
Example
int i = 10;
while (i < 5) {
[Link]("This will never be printed");
i++;
Java Do/While Loop
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition
is true. Then it will repeat the loop as long as the condition
is true.
Syntax
do {
// code block to be executed
while (condition);
Note: The semicolon ; after the while condition is required!
Do/While Example
The example below uses a do/while loop. The loop will always
be executed at least once, even if the condition is false,
because the code block is executed before the condition is
tested:
Example
int i = 0;
do {
[Link](i);
i++;
while (i < 5);
Do not forget to increase the variable used in the
condition (i++), otherwise the loop will never end!
Condition is False from the Start
In the while loop chapter, we saw that if the condition
is false at the beginning, the loop never runs at all.
The do/while loop is different: it will always run the code
block at least once, even if the condition is false from the
start.
In the example below, the variable i starts at 10, so i < 5 is
false immediately. Still, the loop runs once before checking the
condition:
Example
int i = 10;
do {
[Link]("i is " + i);
i++;
} while (i < 5);
While Loop Examples
To demonstrate a practical example of the while loop, we
have created a simple "countdown" program:
Example
int countdown = 3;
while (countdown > 0) {
[Link](countdown);
countdown--;
}
[Link]("Happy New Year!!");
To demonstrate a practical example of the while
loop combined with an if else statement, let's say we play a
game of Hello:
Example
Print "Hello!" If the dice number is 6:
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
[Link]("No Hello.");
} else {
[Link]. println("Hello!");
dice = dice + 1;
Java For Loop
When you know exactly how many times you want to loop
through a block of code, use the for loop instead of
a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
Statement 1 is executed (one time) before the execution of
the code block.
Statement 2 defines the condition for executing the code
block.
Statement 3 is executed (every time) after the code block has
been executed.
Print Numbers
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++) {
[Link](i);
}
Example explained
Statement 1 sets a variable before the loop starts: int i =
0
Statement 2 defines the condition for the loop to run: i <
5. If the condition is true, the loop will run again; if it is
false, the loop ends.
Statement 3 increases a value each time the code block
has run: i++
Print Even Numbers
This example prints even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
[Link](i);
}
Sum of Numbers
This example calculates the sum of numbers from 1 to 5:
Example
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
[Link]("Sum is " + sum);
Countdown
This example prints a countdown from 5 to 1:
Example
for (int i = 5; i > 0; i--) {
[Link](i);
}
For Loop With False Condition
Just like a while loop, a for loop may also never run. If the
condition is false right from the start, the code inside the loop
will be skipped entirely:
Example
for (int i = 10; i < 5; i++) {
[Link]("This will never be printed");
In this example, the loop starts with i = 10. The condition i <
5 is already false, so the loop body is skipped, and nothing is
printed.
Nested Loops
It is also possible to place a loop inside another loop. This is
called a nested loop.
The "inner loop" will be executed one time for each iteration of
the "outer loop":
Example
// Outer loop
for (int i = 1; i <= 2; i++) {
[Link]("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
[Link](" Inner: " + j); // Executes 6 times (2 * 3)
Multiplication Table Example
This example uses nested loops to print a simple multiplication
table (1 to 3):
Example
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link](i * j + " ");
}
[Link]();
}
The for-each Loop
There is also a "for-each" loop, which is used exclusively to
loop through elements in an array (or other data structures):
Syntax
for (type variableName : arrayName) {
// code block to be executed
The for-each loop is simpler and more readable than a
regular for loop, since you don't need a counter (like i <
[Link]).
The following example prints all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
[Link](car);
Here is a similar example with numbers. We create an array of
integers and use a for-each loop to print each value:
Example
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
[Link](num);}
Real-Life Examples
To demonstrate a practical example of the for loop, let's
create a program that counts to 100 by tens:
Example
for (int i = 0; i <= 100; i += 10) {
[Link](i);
In this example, we create a program that only print even
values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
[Link](i);
And in this example, we create a program that prints the
multiplication table for a specified number:
Example
int number = 2;
// Print the multiplication table for the number 2
for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
}
Here is a simple program that prints the seat numbers in a
theater row:
Example
for (int seat = 1; seat <= 5; seat++) {
[Link]("Seat number: " + seat);
Use a loop to calculate the factorial of a given number:
Example
int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
[Link]("Factorial of " + n + " is " + fact);
// Output: Factorial of 5 is 120