Java For Loop – An Ultimate Guide to Master the Concept

While programming, you might have faced a situation where you need to execute a block of code several numbers of times. Therefore, programming languages come up with some control structures called loops that allow the execution of such complex statements. We have covered the concepts of loops in our article of Java Loops. We included the general introduction to “for Loop in Java.”

In this article, we will uncover every minute detail of the “for loop” in Java with examples and will explore different scenarios in which we use this loop.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is for loop in Java?

The “for” loop in Java is an entry-controlled loop that facilitates a user to execute a block of a statement(s) iteratively for a fixed number of times. The number of iterations depends on the test-condition given inside the “for” loop.

The Java “for” loop is one of the easiest to understand Java loops. All the elements of its loop-control that is, initialization, test-expression, and update-expression, gather at one place, that is, on the top of the loop within the round brackets().

The syntax of for loop is:

for(initialization expression(s) ; test-expression ; update-expression(s))
{
    body of the for-loop ;
}

How does the for loop work?

1. The initialization expression of the “for” loop executes only once.

2. After that, the test expression or test-condition executes. The test expression is a boolean expression.

3. If the test expression evaluates to true,

  • Statements inside the body of for loop start executing.
  • Then, the update expression executes.
  • After the update expression, again, the test expression is evaluated.
  • If the test expression evaluates to true, code inside the body of for loop executes and again the update expression executes.
  • This process goes on until the test expression results in false.

4. The “for” loop terminates if the test expression is false.

The following figure shows the working of Java “for” loop:

Example of Java “for” loop:

int x = 0;
for( x = 1 ; x <= 10 ; x++ )
{
         System.out.println(Value of x: “ +x);
}

Code to illustrate the use of for statement/loop:

package com.techvidvan.forloop;
public class ForLoopDemo
{
        public static void main(String args[])
        {
                int i;
                for(i = 1; i <= 10; i++)
                {
                        System.out.println("The value of i is: "+i);
                }
        }
}

Output:

The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
The value of i is: 6
The value of i is: 7
The value of i is: 8
The value of i is: 9
The value of i is: 10

Rules of using for Loops in Java

There are several rules that a programmer must follow in order to implement “for” loops in Java:

1. Variables declared in the initialization block should be of the same type

Each variable in the initialization must be of the same datatype.

We can’t write like this:

for(int x = 0, long y = 1; y < 5; y++)

If we write the above statement, we will get an error like this:

Syntax error on token “long”, delete this token

Code to explain this rule:

public class MyClass
{
    	public static void main(String[] args)
    	{
    	    	for (long x = 0, y = 1; y <= 5; y++)
    	    	{
    	    	    	System.out.println(y+ " ");
    	    	}
    	}
}

Output:

1
2
3
4
5

2. Variables declared inside the initialization block are accessible only within the loop

When we declare any variable inside the for loop, we can not access it after the loop statement is over. The reason is that this variable is declared within a block of statement and therefore its scope becomes the body of the loop. Therefore, we can not access it outside the loop body.

Take a quick sneak peak on Java Variables in detail with Techvidvan.

Code to explain this rule:

public class MyClass
{
  public static void main(String args[])
  {
    for(int i = 0; i < 3 ; i++)
    {
      System.out.println(i + " ");
    }
    System.out.println( "Value of i is " +i );
    //Accessing i after the loop body gives an error
  }
}

Output:

Error: x cannot be resolved to a variable

Correct code to access the variable after the loop body is:

public class MyClass
{
  public static void main(String args[])
  {
    int i;
    for(i = 0; i < 3 ; i++)
    {
      System.out.println(i + " ");
    }
  System.out.println("Value of x is " +i);
  }
}

Output:

0
1
2
Value of i is 3

Manipulating for loops in Java

1. Multiple Initializations and Update Expressions

We can use multiple initializations and/or update expressions inside a “for” loop. But, these multiple expressions inside the “for” loop should be separated by commas.

Code to explain this concept:

public class Example
{
  public static void main(String args[])
  {
    int x1 = 2;
    for(long x2=0, y = 0; x1 < 10 && x2 < 10; x1++, x2++)
    {
      System.out.println("Value of x2 is: " +x2);
    }
    System.out.println("Value of x1 is: " +x1);
  }
}

Output:

Value of x2 is: 0
Value of x2 is: 1
Value of x2 is: 2
Value of x2 is: 3
Value of x2 is: 4
Value of x2 is: 5
Value of x2 is: 6
Value of x2 is: 7
Value of x1 is: 10

The above code contains two initialization expressions x2 = 1 and y = 0 and two update expressions x1++ and x2++. These multiple expressions execute in a sequence.

2. Redeclaration of a variable in an initialization block

We can redeclare the variable in the initialization block in the “for” loop even if we have already declared it outside the “for” loop.

Code to explain this concept:

public class Example
{
  public static void main(String args[])
  {
    int x=0, y=10;
    //changing the values of x and y in the initialization block
    for(y=0, x=1; x<10; x++)
    {
      System.out.println("Value of x is: "+x);
    }
  }
}

Output:

Value of x is: 1
Value of x is: 2
Value of x is: 3
Value of x is: 4
Value of x is: 5
Value of x is: 6
Value of x is: 7
Value of x is: 8
Value of x is: 9

3. Optional Expressions

In a “for” loop, you can skip initialization expressions, test expressions and, update expressions. You can omit any or all of these expressions in a “for” loop. For example, you have already initialized the loop variables and you want to omit the initialization expression then you can write “for” loop as follows:

for( ; test-expression ; update-expression(s))
         loop-body

The semicolon (;) must be present even if you skip the initialization expression.

Code to explain the above concept:

public class ForLoopDemo
{
  public static void main(String args[])
  {
    int i = 1, sum = 0 ;
    for( ; i <= 10 ; sum +=i, ++i )
      System.out.println(i);
    System.out.println("The sum of first 10 numbers is: " +sum) ;
  }
}

Output:

1
2
3
4
5
6
7
8
9
10
The sum of first 10 numbers is: 55

Similarly, we can also omit the test expressions and update expressions. For example,

for( x = 0 ; x != 25 ; )
x += 5 ;

If the variable x has already been initialized, then we can write the above loop as,

for( ; x != 25 ; )
x += 5;

Tip: The loop-control expressions in a for loop statement are optional, but semicolons must be there.

4. Infinite loop

We can also create an infinite loop can be created by skipping the test-expression as shown below:

Code to illustrate an infinite for loop:

public class ForLoopDemo
{
        public static void main(String args[])
        {
                int x;
                for( x = 10 ; ; x-- )
                System.out.println(“This is an infinite loop”);
        }
}

Output:

This is an infinite loop…

We can also skip all the three expressions to create an infinite loop:

public class InfiniteLoop
{
  public static void main(String args[])
  {
    for( ; ; )
      System.out.println("This is an infinite loop") ;
  }
}

Output:

This is an infinite loop…

5. Empty “for” loop

When the loop-body of the for loop contains no statement, then it is called an empty loop. In such cases, a Java loop contains a null statement that is, an empty statement.

Example of an empty loop:

for( x = 0 ; x <= 10 ; x++) ; //See,the loop body contains a null statement

An empty “for” loop finds its applications in the time delay loop where there is a need to increment or decrement the value of some variable without doing anything else, just for introducing some delay.

6. Multiple statements in the loop body

The loop body of the for loop can contain multiple statements. These statements are executed in the sequence.

Code to explain multiple statements in a loop body:

public class ForLoopDemo
{
 	public static void main(String args[])
 	{
 	 	int i,sum;
 	 	for(i = 1 , sum = 0; i <= 5; ++i)
 	 	{
 	 	 	//loop body has multiple statements.
 	 	 	System.out.println("The value of i is: "+i) ;
 	 	 	sum = sum + i;
 	 	}
 	 	System.out.println("The sum of the first 5 numbers is: " +sum) ;
 	}
}

Output:

The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
The sum of the first 5 numbers is: 15

Nested for Loops in Java

Nested for loop is a for- loop that contains another for-loop in its body. In a nested loop, the inner loop must terminate before the outer loop.

Code to understand nested for loop:

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

Output:

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

Enhanced for loop: Java “for-each” Loop

An Enhanced for loop is useful while traversing or iterating an Array or a Collection in Java. It is easier to use, write, and understand as compared to a simple “for” loop because we do not need to increment the value and use a subscript notation. The for-each loop works on the basis of elements, not the index of the element. It one by one returns the elements in the defined variable.

Enhance your knowledge by exploring Arrays in Java in detail with Techvidvan.

Syntax of for-each loop:

for(dataType variableName: arrayName)
{
        //code to be executed
}

Code to understand for-each loop in 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[ ] = {10, 20, 30, 40, 50};

    //Printing array using for-each loop
    for(int iterator : arr)
    {
      System.out.println(iterator);
    }
  }
}

Output:

10
20
30
40
50

Labeled for Loop in Java

Using the Labeled for loop in Java, we can have the name of each Java “for” loop. To do so, we put a label before the “for” loop. Labeled for loop is useful if we have nested for loop so that we can break or continue from the specific “for” loop with the help of the label. Usually, break and continue keywords are useful for breaking or continuing with the innermost for loop only.

Syntax:

labelname:
for(initialization; test-condition; update-expression)
{
         //code to be executed
}

Code to understand the labeled for loop in Java:

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

Output:

1 1
1 2
1 3
2 1

Summary

Loops in Java are crucial when we want to execute the same block of code multiple times. Java for loop is the easiest loops in Java that has all the expressions in a single line.

In this article, we learned the for loop in Java in depth. There are several variations in Java for loop which increases the flexibility and efficiency of the “for” loop. With these manipulations, we can use the for loop in many different ways to get the desired results. We can also have an empty loop, an infinite loop, a nested loop, and a labeled loop in a “for” loop in Java.

In this article, we covered each variation in the for loop with examples. After reading this article, you will surely be able to smoothly use the “for” loop in Java programs.

Thank you for reading our article. Do share your feedback through the comment section below.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.