For Loop:

In Java, the for loop is a control inflow statement that allows you to repeatedly execute a block of code a specified number of times. It is particularly useful when you already know the number of iterations.

forLoop.java
for (initialization; condition; update) {
    // Code to be executed repeatedly
}

initialization - assign value to a variable.
condition - check condition.
update - change the value of variable.

forLoop.java
public class Main {
  public static void main(String[] args) {
      
    for (int i = 1; i <= 5; i++) {
        System.out.println("Count is: " + i);
    }
 
  }
}

In this Example:

  • Statement-1 shows i=0.
  • Statement-2 checks condition, i is less than 5(true), move inside loop and print count.
  • Statement-3 will increment i, now i=1. Statement-2 checks condition, i is less than 5(true), move inside loop and print count.
  • Statement-3 will increment i, now i=2. Statement-2 checks condition i is less than 5(true), move inside loop and print count.
  • Statement-3 will increment i, now i=3. Statement-2 checks condition i is less than 5(true), move inside loop and print count.
  • Statement-3 will increment i, now i=4. Statement-2 checks condition i is less than 5(true), move inside loop and print count.
  • Statement-3 will increment i, now i=5. Statement-2 checks condition i is less than 5(false), loop will terminate and control moves to next line.

Infinite For Loop:

If you put the double semicolon inside paranthesis, it will become infinite for loop.


forLoop.java
public class Main {
    public static void main(String[] args) {
        
      for (;;) {
          System.out.println("Hi there!");
      }
   
    }
  }

Nested For Loop:

Nested loops are loops within loops. When we have a nested loops then, when outer loop runs one-time, inner loops complete its all iterations. After that control moves to the outer loop. Again, the outer loop runs a second time and inner loop completes its all iterations. This process will continue until the outer loop completes its all iterations.


forLoop.java
public class Main {
    public static void main(String[] args) {
        
        for (int i = 1; i <= 3; i++) {
          System.out.println("Outer: " + i); 
          
          for (int j = 1; j <= 3; j++) {
            System.out.println("\nInner: " + j); 
          }
        } 
   
    }
  }

For each Loop:

In Java, the "for-each" loop, also known as the enhanced for loop, provides a convenient way to iterate through elements in an array or collection (such as ArrayList, List, Set, or Map) without the need for explicit index-based iteration.


forLoop.java
public class Main {
    public static void main(String[] args) {
        
      String[] fruits = {"Apple", "Mango", "Banana"};
      for (String fruit : fruits) {
          System.out.println(fruit);
      }
   
    }
}