For Loop in Java
The for loop in Java is a control flow statement that is used to execute a block of code repeatedly for a specific number of times. It is commonly used when the number of iterations is already known.
The Java for loop provides a simple way to repeat tasks by using initialization, condition, and increment or decrement expressions in a single statement.
What is For Loop in Java?
A for loop in Java is an iteration statement that allows programmers to execute the same block of code multiple times until a given condition becomes false.
It is mainly used for looping through arrays, collections, and performing repetitive operations.
Syntax of For Loop in Java
for (initialization; condition; increment/decrement) {
// code to execute
}
Components of For Loop
Initialization
Initializes the loop variable and executes only once at the beginning.
Condition
Checks whether the loop should continue or stop.
Increment/Decrement
Updates the loop variable after every iteration.
How For Loop Works in Java?
- The initialization part executes first.
- The condition is checked before every iteration.
- If the condition is true, the loop body executes.
- The increment or decrement operation updates the variable.
- The loop stops when the condition becomes false.
Example of For Loop in Java
public class Main {
public static void main(String[] args) {
for(int i = 1 ; i <= 5 ; i++) {
System.out.println(i);
}
}
}
2
3
4
5
Nested For Loop in Java
A nested for loop is a loop inside another loop. The inner loop executes completely for each iteration of the outer loop.
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.println(i +" " + j);
For Loop Example: Print Even Numbers
public class Main {
public static void main(String[] args) {
for(int i = 1 ; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
4
6
8
10
Advantages of For Loop in Java
Easy Iteration
Helps execute repetitive tasks easily.
Less Code
Reduces the amount of repeated code.
Better Control
Provides control over loop initialization and execution.
When to Use For Loop?
- When the number of iterations is known.
- When working with arrays and collections.
- When performing repeated calculations.
- When creating patterns and tables.