For Loop in Java

The for loop in Java is utilized to repeatedly execute a specific part of a program. It offers a convenient way to iterate a block of code multiple times. When the number of iterations is predetermined or fixed, the for loop is recommended for its concise and efficient syntax.

There are three types of (for loops) in Java.

  • Simple for loop
  • For-each or Enhanced for Loop
  • Labeled for Loop

Simple for Loop in Java:

A basic for loop in Java follows a similar structure as in C/C++. It includes four essential components: variable initialization, condition checking, and incrementing or decrementing the value. These parts work together to control the loop’s execution.

Initialization: The initialization is an initial condition that is executed once at the beginning of the loop. It can involve initializing a variable or using an already initialized variable. This step is optional.

Condition: The condition is evaluated each time to test if the loop should continue executing. It determines whether the loop’s execution should continue or not. The condition must return a boolean value, either true or false. This step is optional.

Increment/Decrement: The increment or decrement operation modifies the value of the variable after each iteration of the loop. It allows for controlling the loop’s iteration and progression. This step is optional.

Statement: The statement within the loop is executed repeatedly until the condition evaluates to false. It defines the actions or operations to be performed during each iteration of the loop.

Syntax:

for(initialization; condition; increment/decrement){    
//statement or code to be executed    
}

Example:

ForExample.java

//Java Program to demonstrate the example of for loop  
//which prints table of 1  
public class ForExample {  
public static void main(String[] args) {  
    //Code of Java for loop  
    for(int i=1;i<=10;i++){  
        System.out.println(i);  
    }  
}  
}

Output:

1
2
3
4
5
6
7
8
9
10

Nested for Loop in Java:

In Java, when a for loop is placed inside another loop, it is referred to as a nested for loop. The inner loop executes in its entirety each time the outer loop executes.

Example:

NestedForExample.java

public class NestedForExample {  
public static void main(String[] args) {  
//loop of i  
for(int i=1;i<=3;i++){  
//loop of j  
for(int j=1;j<=3;j++){  
        System.out.println(i+" "+j);  
}//end of i  
}//end of j  
}  
}

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Example 1:

PyramidExample.java

public class PyramidExample {  
public static void main(String[] args) {  
for(int i=1;i<=5;i++){  
for(int j=1;j<=i;j++){  
        System.out.print("* ");  
}  
System.out.println();//new line  
}  
}  
}

Output:

* 
* * 
* * * 
* * * * 
* * * * *

Pyramid Example 2:

PyramidExample2.java

public class PyramidExample2 {  
public static void main(String[] args) {  
int term=6;  
for(int i=1;i<=term;i++){  
for(int j=term;j>=i;j--){  
        System.out.print("* ");  
}  
System.out.println();//new line  
}  
}  
}

Output:

* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

for-each Loop

The for-each loop in Java is designed for traversing arrays or collections. It offers a simplified syntax compared to the traditional for loop since there is no need for manual incrementing or subscript notation.

The for-each loop operates based on elements rather than indices. It iterates through the elements of an array or collection and assigns each element to a defined variable one at a time.

Syntax:

for(data_type variable : array_name){    
//code to be executed    
}

Example:

ForEachExample.java

//Java For-each loop example which prints the  
//elements of the array  
public class ForEachExample {  
public static void main(String[] args) {  
    //Declaring an array  
    int arr[]={12,23,44,56,78};  
    //Printing array using for-each loop  
    for(int i:arr){  
        System.out.println(i);  
    }  
}  
}

Output:

12
23
44
56
78

Labeled For Loop in Java:

In Java, it is possible to assign a name, or label, to a for loop by placing the label before the loop declaration. This labeling technique becomes particularly useful when working with nested loops, as it allows for targeted usage of the break and continue statements within a specific loop.

Syntax:

labelname:    
for(initialization; condition; increment/decrement){    
//code to be executed    
}

Example:

LabeledForExample.java

//A Java program to demonstrate the use of labeled for loop  
public class LabeledForExample {  
public static void main(String[] args) {  
    //Using Label for outer and for loop  
    aa:  
        for(int i=1;i<=3;i++){  
            bb:  
                for(int j=1;j<=3;j++){  
                    if(i==2&&j==2){  
                        break aa;  
                    }  
                    System.out.println(i+" "+j);  
                }  
        }  
}  
}

Output:

1 1
1 2
1 3
2 1

LabeledForExample2.java

public class LabeledForExample2 {  
public static void main(String[] args) {  
    aa:  
        for(int i=1;i<=3;i++){  
            bb:  
                for(int j=1;j<=3;j++){  
                    if(i==2&&j==2){  
                        break bb;  
                    }  
                    System.out.println(i+" "+j);  
                }  
        }  
}  
}

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Infinitive for Loop in Java:

In Java, if two semicolons (;; ) are used in the for loop declaration, it creates an infinite loop. An infinite loop is a loop that continues indefinitely until it is forcefully terminated.

Syntax:

for(;;){  
//code to be executed  
}

Example:

ForExample.java

//Java program to demonstrate the use of infinite for loop  
//which prints an statement  
public class ForExample {  
public static void main(String[] args) {  
    //Using no condition in for loop  
    for(;;){  
        System.out.println("infinitive loop");  
    }  
}  
}

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Difference between for Loop, while Loop, and do-while Loop:

Comparison for loop while loop do-while loop
Introduction The Java for loop is a control flow statement that iterates a part of the program multiple times. The Java while loop is a control flow statement that executes a part of the programs repeatedly based on a given boolean condition. The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
When to use If the number of iterations is fixed, it is recommended to use for loop. If the number of iterations is not fixed, it is recommended to use a while loop. If the number of iterations is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntax for(init;condition;incr/decr){
// code to be executed
}
while(condition){
//code to be executed
}
do{
//code to be executed
}while(condition);
Example //for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
//while loop
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
//do-while loop
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
The syntax for infinitive loop for(;;){
//code to be executed
}
while(true){
//code to be executed
}
do{
//code to be executed
}while(true);

For a deeper understanding of concepts like the For Loop in Java, we recommend following tutorials.freshersnow.com.