Search Placementyogi.com
 

For Loop in Java

The for loop in java allows us to execute a set of statements a specific number of times.

Syntax of for loop in Java:

for(initialization;condition;iteration)
{
	//body
}

If there is just one statement in the body , the braces are not required.

For Loop Control Flow in Java

Control Flow of for loop in Java:

  1. The initialization statement is executed first.It declares and initializes the value of the "loop control variable" which acts as the counter of the for loop. It executes only once at the beginning of the for loop.
  2. The condition statement is executed next and tests the value of the loop control variable and decides whether the body of the for loop can be executed. It can only be a boolean expression. If the condition evaluates to true , the body is executed otherwise the loop terminates and the statement after the for loop is executed.
  3. The body of the for loop is executed next.
  4. Once the control finishes executing the last statement of the body, the control goes to the iteration statement. It updates/modifies the value of the loop control variable/ counter and prepares for the next iteration.
  5. Then the control again enters the condition statement and checks whether the updated control variable still satisfies the condition. 

Thus, the steps 2, 3 and 4 are executed in a loop until the condition evaluates to false.

Example of for loop in Java:

public class ForLoop
{
	public static void main(String[] args)
	{
		for(int i=5;i<10;i++)
		{
			System.out.println("i="+i);
		}
		System.out.println("After for loop");
	}
}

Output:

i=5

i=6

i=7

i=8

i=9

After for loop

 

Explanation: 

Notice that the variable i is declared inside the initialization statement of the for loop. This means that the scope of "i" is only inside the for loop.

First, i is initialized to 5. Then i<10 condition is tested and since it is true, the control enters the body.

The statement println is executed and i=5 is printed.

Then, the iteration statement (i++) is executed and increments the value of i to 6.

This updated value of i is tested again in the condition statement (i<10) , since 6<10 is true, the control again enter the body and prints i=6.

This goes on, till i=9 is printed.

When the control enters the iteration statement this time, i becomes 10.

The condition is tested and i<10 becomes false.

The control comes out of the for loop and "After for loop" is printed!

Try to go through the above explanation once more to grasp the whole concept thoroughly. This is one of the most important concept and many interview questions are asked from for loop based on the control flow.

Variations of for loop in Java

The initialization statement, condition statement and iteration statement are not compulsory, and they can be kept empty.

We can rewrite the above program in these way also:

Variation 1: Without the initialization and iteration statement
public class ForLoop
{
	public static void main(String[] args)
	{
		int i=5;
		for(;i<10;)
		{
			System.out.println("i="+i);
			i++;
		}
		System.out.println("After for loop");
	}
}

In the above program, we have intentionally kept the initialization and iteration part empty. But, T achieve this, we had to write the initialization statement before the for loop and had to increment the counter inside the body of the loop.

Variation 2: Without the Condition Statement

In the following program, we have eliminated the condition statement also, but we have to modify the body of the for loop so that the it does not become an infinite loop. This is done by using the break statement inside the for loop body. when the value of i becomes 10 , the break statement terminates the for loop. We will discuss the break statement in the next topic.

public class ForLoop
{
	public static void main(String[] args)
	{
		int i=5;
		for(;;)
		{
			System.out.println("i="+i);
			i++;
			if (i==10) 
				break;
		}
		System.out.println("After for loop");
	}
}
Variation 3: Infinite loop in Java using for 

The following program is an infinite loop as all the three parts of the for loop are kept empty.

public class ForLoop
{
	public static void main(String[] args)
	{
		for(;;)
		{
			System.out.println("inside Infinite Loop");
		}
	}
}

Enhanced For Loop in Java (foreach loop in Java)

The creators of java came up with another form of for loop called enhanced for loop.

The enhanced for loop can be used with collection of objects such as arrays, to iterate over the elements in a sequential manner.

The programmer does not have to worry about the length of the array, the foreach loop takes care of it automatically.

There is no new keyword foreach in java, it is implemented just as an enhanced for loop i.e. a variation of the for loop.

The syntax of enhanced for loop in Java:

for (type itr-var : collection)
{
	statements in body
}

The above syntax can be read as:

for each item in collection execute the statements in the body.

Here, "type" specifies the data type of the elements in the collection object.

itr-var is a local variable in to which each of the elements of the collection is copied one by one in each iteration.

So, if there are 5 items in an array, 

  1. The first item is copied in to the itr-var variable  in the first iteration, 
  2. The second element is the next iteration and so on. 
  3. In the last iteration, the 5th item is copied into the itr-var variable. 
  4. After this, the for loop ends as there are no items in the array.

 

Important point:

The iteration variable is just a copy of the element of the array, any change to it will not change the original array.

 

Example of foreach loop in Java:

public class ForLoop
{
	public static void main(String[] args)
	{
		int []arr={1,2,3,4,5};
		for(int item : arr)
		{
			System.out.println("item="+item);
		}
		System.out.println("After the for each loop");
	}
}

Output:

item=1

item=2

item=3

item=4

item=5

After the for each loop

 

Advantages of for each loop in Java

  1. It eliminates the need of a loop counter variable.
  2. The start and ending conditions are not needed, foreach takes care of it automatically.
  3. There is no need to calculate the length of the array (or any collection object)

The above program can be written using the conventional for loop in this way:

public class ForLoop
{
	public static void main(String[] args)
	{
		int []arr={1,2,3,4,5};
		for(int i=0;i<arr.length; i++)
		{
			System.out.println("item="+arr[i]);
		}
		System.out.println("After the for each loop");
	}
}
Banner to LogicGuns.com

Hide Page Information

For Loop in Java