Show List
Loops in Java
Loop is used to repeatedly execute a block of statements. Loops are handy because they save time in writing code, help reduce errors, and make code more readable.
There are following types of loops in Java:
For Loop
- For loop is used to execute set of statements for specific number of times
- In the example below the execution starts when the value of i = 0 and continues till i <= 10 and value of i increments by 1 with each iteration.
for (int i = 0; i <= 10; i = i + 1) {
System.out.println(i);
}
For Each Loop
- It is used to loop through elements of an Array and Collections.
- It is also known as enhanced for loop.
- In the example below there are four elements in the numbers array. So the loop executes four times printing each number.
// create an array
int[] numbers = {3, 9, 5, -5};
// for each loop
for (int number: numbers) {
System.out.println(number);
}
While Loop
- It loops through the statements till the specified condition is true
- In the example below the execution will start with the value of i as 1 and repeat till i <= n. With each iteration the value of i is being incremented by 1. So the loop will execute 100 times.
int i = 1, n = 100;
// while loop from 1 to 100
while(i <= n) {
System.out.println(i);
i++;
}
Do While Loop
- It is similar to while loop however the body is executed first before the condition is checked.
- In the example below the execution starts without checking any condition and condition i <= n is checked only after the iteration. Value of i increments by 1 with each iteration so this loop will execute 5 times.
int i = 1, n = 5;
// do...while loop from 1 to 5
do {
System.out.println(i);
i++;
} while(i <= n);
Leave a Comment