Loops in Java
Loops in Java
Syntax:
Syntax:
ForEachExample.java
Note: The break and continue keywords breaks or continues the innermost for loop respectively.
Syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
LabeledForExample.jav
a LabeledForExample2.java
//A Java program to demonstrate the use of labeled for loop
1. public class LabeledForExample2 {
1. public class LabeledForExample {
2. public static void main(String[] args) {
2. public static void main(String[] args) {
3. //Using Label for outer and for loop
3. aa:
Output: Output:-
11
11
12
12
13
13 21
21 31
32
33
If you use break bb;, it will break inner loop only which is the default behaviour of any loop.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to
update expression. When the condition becomes false, we exit the while loop.
Example:
i <=100
2. Update expression: Every time the loop body is executed, this expression increments or decrements loop variable.
Example:
i++;
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize and increment
the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.
WhileExample.java
Output:
1
2
3
4
5
6
7
8
9
10
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at
the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update
expression. As soon as the condition becomes false, loop breaks automatically.
Example:
i <=100
2. Update expression: Every time the loop body is executed, the this expression increments or decrements loop variable.
Example:
i++;
Note: The do block is executed at least once, even if the condition is false.
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to
initialize and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.
DoWhileExample.java
Output:
1
2
3
4
5
6
7
8
9
10