For Loop In JAVA
For loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
There are three types of for loops in java.
- For Loop
- For-each or Enhanced For Loop
For Loop Basic Steps
- Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
- Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
- Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
- Increment/ Decrement: It is used for updating the variable for next iteration.
- Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.
Java For Loop
The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.
Syntax:
for (initialization; condition; increment/decrement)
{
//your statement
}
Example
public class ForLoopDemo {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output :
1
2
3
4
5
6
7
8
9
10
Series:
Java Tutorials Hub
