For loop in java with example is widely used loop in programming language.
It also works like the while loop as we seen in previous tutorial.
For loop in java
for loop contains mainly 3 expressions.
The first expression is treated as statement and executed, then second expression is condition which is evaluated and checked to execute body of loop. At last third expression is increment or decrements which is performed after every iteration.
For loop syntax java
for(expression 1; expression 2; expression 3)
// Statement 2
In above syntax we can we for loop having 3 expressions and block of statement in curly braces.
Flow of For loop in java
For loop example
In above example for loop in java , we written for loop with expression 1 s=1 expression 2 s<3 and expression 3 s++.for loop iterated for 2 time and prints output as s=1 ,s=2.
For loop in java program
public class Main
public static void main (Stringargs)
System.out.println("For loop execution ");
for(i = 0 ; i < 5; i ++)
System.out.println("for loop executed");
1. In above program we demonstrate for loop .
2. First we take variable declare the variable I.
3. Next we write for loop with 3 expressions. First is i = 0 which initialize i value . Then second expression condition i < 5 .
4. Now condition is checked i = 0 < 5 , this condition is true so statement in for loop executed
5. Now flow goes to increment expression i ++ . Value of i is incremented now i = 1
6. Next condition is checked i=1 < 5 , condition true again statement executed.
7. Similarly , loop iterated till value of i = 5
8. In this case i=5 , condition false so execution comes out of the loop and rest of code executed.