LogIn
I don't have account.

for loop in java

DevSniper
151 Views

for loop is a fundamental control flow statement of Java. for loop is used to run some block of code several times based on certain condition. It offers a structured and efficient way to handle repetitive tasks.

for (statement1; statement2; statement3) 
{
    // loop body
}
  • statement1 (initialization) : Initializes the for loop control variable, typically a counter variable which is used to control for loop iteration. This part is executed only once when the loop begin.
  • statement2 (condition) : it execute before every execution of the loop body. Here we define condition of the execution of loop body. if the condition is false we stop execution of the loop body and terminate loop.
  • statement3 (update) : it execute after every execution of the loop body. mostly here we modifies the loop control variable after each iteration of the loop body.
  • for loop is used to execute a block of code (loop body) several times.
  • for loop is a entry control loop it verifies condition before executing of the loop body.
  • for loop simplifies repetitive tasks.
  • for loop widely used for iterating over arrays, collections, or performing a fixed number of iterations.
  • Simple for loop
  • Enhanced for loop
  • Nested for loop
  • Infinite for loop

Simple for loop

for loop consists of four parts
1. initialization
2. condition
3. statement or loop body or code block
4. update or Increment/Decrement
public class RebootMemory 
{
    public static void main(String[] args) 
    {
        //Increment
        for(int i=3; i<10; i++) 
        {
            System.out.print(i+" ");
        }
        System.out.println();
        //Decrement
        for(int i=10; i>3; i--) 
        {
            System.out.print(i+" ");
        }
    }
}
3 4 5 6 7 8 9 
10 9 8 7 6 5 4 

Enhanced for loop (foreach)

Enhanced for loop is also known as foreach loop. it is Introduced in Java SE 5. It is a simplified and easy way to iterate over collections and arrays in Java. It enhances code readability by focusing on the elements being processed rather than loop mechanics.

Example: Iterating Over an Array

public class RebootMemory 
{
    public static void main(String[] args) 
    {
        int[] numbers = {11, 12, 13, 14, 15};
        for (int num : numbers) {
            System.out.println("Number is: " + num);
        }
    }
}
Number is: 11
Number is: 12
Number is: 13
Number is: 14
Number is: 15

Example : Iterating Over Collections

The enhanced for loop can also iterate over collections like ArrayList , HashSet, LinkedList etc

import java.util.ArrayList;
public class RebootMemory 
{
    public static void main(String[] args) 
    {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Orange");
        fruits.add("Banana");
        for (String fruit : fruits) {
            System.out.println("Fruit :- " + fruit);
        }
    }
}
Fruit :- Apple
Fruit :- Orange
Fruit :- Banana

Enhanced for loop Considerations and Limitations

  • Read-only :- The enhanced for loop is suitable only for iterating over elements. It does not allow modification of elements or access to indices during iteration.
  • Null Handling :- if collection or array that you are iterating is null then it will throw NullPointerException.

Nested for loop

if we place one loop inside another for loop this is called nested for loop. inner for loop executed completely for every outer for loop execution.

public class RebootMemory 
{
    public static void main(String[] args) 
    {
        for( int i=1 ; i<=2; i++ ) {
            System.out.println("Inside Outer loop i : "+i);
            for(int j= 1; j<=3 ; j++) {
                System.out.println("=>  inside inner loop i :- "+i+" and j : "+j);
            }
        }
    }
}
Inside Outer loop i : 1
=>  inside inner loop i :- 1 and j : 1
=>  inside inner loop i :- 1 and j : 2
=>  inside inner loop i :- 1 and j : 3
Inside Outer loop i : 2
=>  inside inner loop i :- 2 and j : 1
=>  inside inner loop i :- 2 and j : 2
=>  inside inner loop i :- 2 and j : 3

Infinite for loop

if we keep statement 2 (condition) empty OR define a condition that never becomes false, loop become Infinite Loop

for( ; ; ) 
{
   // loop body
}
for(int i=5 ; ;) 
{
   // loop body
}
for(int i=5 ; ;i++) 
{
   // loop body
}
for( int i=1 ; i>0;  ) 
{
    // loop body
}