Open In App

For Loop in Java | Important points

Last Updated : 17 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do-while loop or we can call it basically three types of loops in some books as for-each loop is treated as enhanced for loop. Let us discuss for loop in details.

Generally, we tend to use while loops as we do get a better understanding if we are into learning loops but after a saturation, we as programmers tend to tilt towards for loop as it is cleaner and foundations are carried out in a straight go for which we have to carefully grasp syntax as follows:

Syntax: It consists of three parts namely as listed:

  • Initialization of variables
  • Specific condition as per requirement over which these defined variables are needed to be iterated
  • A terminating part where we generally play with variables to reach to terminating condition state.
for(initialization; boolean expression; update statement) { 
// Body of for loop 
} 

This is generally the basic pilgrimage structure of for loop.

Let’s look at some basic examples of using for loop and the common pitfalls in using for loop which enables us to know even better as internal working will be depicted as we will be playing with codes. 

Usecase 1: Providing expression in for loop is a must

For loop must consist of a valid expression in the loop statement failing which can lead to an infinite loop. The statement 

for ( ; ; ) 
is similar to
while(true)

Note: This above said is crux of advanced programming as it is origin of logic building in programming.

Example

Java




// Java program to illustrate Infinite For loop
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // For loop
        for (;;) {
 
            // Print statement everytime condition holds
            // true making body to execute
            System.out.println("This is an infinite loop");
        }
    }
}


Output: Prints the statement “This is an infinite loop” repeatedly.

This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop
...
...
This is an infinite loop

Usecase 2: Initializing Multiple Variables

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.

Example:

Java




// Java Program to Illustrate Initializing Multiple
// Variables in Initialization Block
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring an integer variable
        int x = 2;
 
        // For loop to iterate
        for (long y = 0, z = 4; x < 10 && y < 10;
             x++, y++) {
            // Printing value/s stored in variable named y
            // defined inside body of for loop
            System.out.println(y + " ");
        }
 
        // Printing value/s stored in variable named x
        // defined outside body of for loop
        System.out.println(x);
    }
}


Output

0 
1 
2 
3 
4 
5 
6 
7 
10

In the above code, there is simple variation in the for loop. Two variables are declared and initialized in the initialization block. The variable ‘z’ is not being used. Also, the other two components contain extra variables. So, it can be seen that the blocks may include extra variables which may not be referenced by each other. 

Usecase 3: Redeclaration of a Variable in the Initialization Block

Suppose, an initialization variable is already declared as an integer. Here we can not re-declare it in for loop with another data type as follows:

Example 1:

Java




// Java Program to Illustrate Redeclaring a Variable
// in Initialization Block
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring an integer variable
        int x = 0;
 
        // Redeclaring above variable
        // as long will not work
        for (long y = 0, x = 1; x < 5; x++) {
 
            // Printing the value inside the variable
            System.out.print(x + " ");
        }
    }
}


Output:

Example3.java:12: error: variable x is already defined in method main(String[])
        for(long y = 0, x = 1; x < 5; x++)

Here, x was already initialized to zero as an integer and is being re-declared in the loop with data type long. But this problem can be fixed by slightly modifying the code. Here, the variables x and y are declared in a different way. 

Example 2:

Java




// Java Program to Illustrate Redeclaring a Variable
// in Initialization Block
 
// Main class
public class GFG {
 
    // main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing variables
        int x = 0;
        long y = 10;
 
        // For loop to iterate over till
        // custom specified check
        for (y = 0, x = 1; x < 5; x++) {
           
            // Printing value contained in memory block
            // of the variable
            System.out.print(x + " ");
        }
    }
}


Output: 

1 2 3 4

Usecase 4: Variables declared in the initialization block must be of the same type

It is just common sense that when we declare a variable as shown below:

 int x, y;

Here both variables are of the same type. It is just the same in for loop initialization block too. 

Example:

Java




// Java program to Illustrate Declaring a Variable
// in Initialization Block
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring integer variable
        // int x;
 
        // Note:  This will cause error;
 
        // Redeclaring x as long will not work
        for (long y = 0, x = 1; x < 5; x++) {
           
            // Printing the value stored
            System.out.print(x + " ");
        }
    }
}


Output

1 2 3 4 

Usecase 5: Variables in the loop are accessible only within

The variables that are declared in the initialization block can be accessed only within the loop as we have as per the concept of the scope of variables. 

Example:

Java




// Java Program to Illustrate Scope of Initializing
// Variables Within the oop
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // x and y scope is declared only
        // within for loop
        for (int x = 0, y = 0; x < 3 && y < 3; x++, y++) {
            // Printing value stored in variable named y
            System.out.println(y + " ");
        }
 
        // Printing value stored in variable named x
        // after inner loop is over
        System.out.println(x);
    }
}


Error:

Example5.java:13: error: cannot find symbol
        System.out.println(x);

In the above example, variable x is not accessible outside the loop. The statement which is commented gives a compiler error. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads