Loops are used to execute a particular block of code several times till a specified condition is reached. Using loops saves time. There are for loop, while loop and do…while loops in Java.
‘for loop‘ is used to execute a particular block of code for a definite number of times. ‘for loop‘ contains an initialization condition, condition expression and an update expression. The following program shows the use of for loop to print numbers from 1 to 10.
package com.company;
public class Loops {
public static void main(String[] args) {
int n = 10;
for (int i = 1; i <= n; ++i) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
‘for-each‘ loop is used to iterate through an array or collection. Its syntax is for (data type variable name: array/collection name). The following program shows the use of for-each loop.
package com.company;
public class Loops {
public static void main(String[] args) {
int[] num = {1,2,3,4,5};
for (int numbers: num) {
System.out.println(numbers);
}
}
}
Output:
1
2
3
4
5
While loop in java executes a block of code to a certain number of times till the condition in the test expression of while statement is true. The following program shows the use of while statement to print the numbers from 1 to 5.
package com.company;
public class Loops {
public static void main(String[] args) {
int n = 1;
while (n < 6) {
System.out.println(n);
n++;
}
}
}
Output:
1
2
3
4
5
The do…while loop is similar to while loop, but the code block is once executed even if the condition in the while statement is false. The following program shows the use of do…while statement.
package com.company;
public class Loops {
public static void main(String[] args) {
int n = 1;
do {
System.out.println(n);
n++;
}
while (n < 6);
}
}