The for
loop in Java is one of the most commonly used loops. It’s ideal when you know in advance how many times you need to iterate through a block of code.
Syntax
1 2 3 |
for(initialization; condition; update) { // code to be executed } |
- Initialization: Initializes a variable, executed once at the beginning.
- Condition: Expression evaluated before each iteration. If it’s true, the loop continues; if false, it stops.
- Update: Updates the variable after each iteration.
Types of for loops
- Basic
for
Loop: Used when the number of iterations is known ahead of time.
1 2 3 |
for (int i = 0; i < 5; i++) { System.out.println(i); } |
Output
1 2 3 4 5 |
0 1 2 3 4 |
- Basic
for
Loop to iterate over Arrays: An index is used variable to access each element of the array.
1 2 3 4 5 |
int[] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } |
Output
1 2 3 4 5 |
1 2 3 4 5 |
- Enhanced
for
Loop (for-each loop): Used to iterate through arrays or collections.
1 2 3 4 |
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); } |
Output
1 2 3 4 5 |
1 2 3 4 5 |
- Infinite
for
Loop: An infinitefor
loop is typically used in scenarios where you need the loop to run continuously until some external condition occurs, such as a user input, a specific event, or a system signal to break the loop. It’s commonly used in:- Server Applications: For waiting and handling incoming requests continuously (e.g., a web server listening for requests).
- Game Loops: In games, where the loop continues to run until the game ends or the user decides to quit.
- Monitoring Systems: For constantly checking sensors or user inputs without a predetermined stop condition.
- Embedded Systems: Often used in microcontrollers and devices where the program runs continuously and only stops when manually reset or powered off.
1 2 3 |
for(;;) { System.out.println("This will run forever!"); } |