A situation occurs where we need to execute our set of statements n number of times again and again until the condition satisfies. Loops are mostly commonly used where a single set of code needs to be executed repetitive times.
1.Java Simple For Loop : The For loop is used to initialize variables, check condition and increament/Decrement.
Syntax of Simple For Loop:
1 2 3 4 5 6 7 |
for(initialization ; condition ; increment/Decrement) { //code that needs to be executed } |
Example :
1 2 3 4 5 6 7 8 9 10 11 |
public class forExample { public static void main(String[] args) { for(int i=1;i<=10;i++){ System.out.println(i); } } } |
OUTPUT :
java for loop example
2.Java for –each loop : For – each loop is mainly used to read complete array or collection in java. We need not increament or decrement the value. The other name for –each loop is dynamic loop, because we are not hard coding the increament or decrement values.
Syntax of for Each Loop:
1 2 3 4 5 6 7 |
for(DataType variable : array) { // code that needs to be executed } |
Example Program on for Each loop :
1 2 3 4 5 6 7 8 |
public class forEachExample { public static void main(String[] args) { int ar[]={10,20,30,40,50}; for(int i:ar){ System.out.println(i); } } } |
OUTPUT :
java for each loop example
Java While Loop : Java while loop is used to iterate the program several times. However the number of iterations are not fixed or known, we can use While loop.
Syntax of While loop :
1 2 3 4 5 6 7 |
While(condition) { //lines of code will execute } |
Example of while loop :
1 2 3 4 5 6 7 8 9 |
public class whileExample { public static void main(String[] args) { int z=1; while(z<=10){ System.out.println(z); z++; } } } |
Output :
java while loop example
Java do-While Loop : The java do-while loop is used when the number of iteration is not fixed and we must have to execute the loop at least once. At this time we will use do-while loop.
Syntax of do-While Loop :
1 2 3 4 5 6 7 8 9 |
do { //code to be executed } While(condition); |
Program on do-while loop :
1 2 3 4 5 6 7 8 9 10 11 |
public class whileExample { public static void main(String[] args) { int z=1; do{ System.out.println(z); z++; } while(z<= 10); } } |
Output :