Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java we have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use āfor loopā in Java.
Syntax of for loop:
for(initialization; condition ; increment/decrement) { statement(s); }
Example of Simple For loop
class ForLoopExample { public static void main(String args[]){ for(int i=10; i>1; i--){ System.out.println("The value of i is: "+i); } } }
The output of this program is:
The value of i is: 10 The value of i is: 9 The value of i is: 8 The value of i is: 7 The value of i is: 6 The value of i is: 5 The value of i is: 4 The value of i is: 3 The value of i is: 2
In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
iā Decrement operation
Infinite for loop
The importance of Boolean expression and increment/decrement operation co-ordination:
class ForLoopExample2 { public static void main(String args[]){ for(int i=1; i>=1; i++){ System.out.println("The value of i is: "+i); } } }
This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the Boolean expression: i>1) so it would never return false. This would eventually lead to the infinite loop condition. Thus it is important to see the co-ordination between Boolean expression and increment/decrement operation to determine whether the loop would terminate at some point of time or not.
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 { public static void main(String args[]){ int arr[]={2,11,45,9}; //i starts with 0 as array index starts with 0 too for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); } } }
Output:
2 11 45 9
Thanks you so much for writing easy to understand code for Java.