Loops in Java

for loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form:

for (initialization; condition; update) {
statements;
}

The for loop defines three types of statements separated with semicolons ( ; ), as follows:

  • Initialization statements
  • Termination condition
  • Update clause (executable statement)

Example:

public class Myclass {
public static void main(String[] args) {
int tableOf = 25;
for (int ctr = 1; ctr <= 5; ctr++) {
System.out.println(tableOf * ctr);
}
}
}
Output:
25
50
75
100
125

The above code will execute five times. It starts with an initial value of 1 for the variable ctr and executes while ctr is less than or equal to 5. The value of ctr will increment by 1 ( ctr++ ).

The code executes for ctr values 1, 2, 3, 4, and 5. Because 6 <= 5 evaluates to false, now the for loop completes its execution without executing the set of statements.

The for loop operates as follows.

Step 1: Initialization. It sets the value of the loop control variable, which acts as a counter that controls the loop. The initialization expression is executed only once.

Step 2: Condition. This must be a Boolean expression. It tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

Step 3: Iteration. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression then executing the body of the loop and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

The update clause executes after all the statements defined within the for loop body. The initialization section, which executes only once, may define multiple initialization statements. The update clause may define multiple statements. But there can be only one termination condition for a for loop.


Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution of the statement.

Example:

public class Myclass {
public static void main(String[] args) {
int num = 9;
boolean divisibleBy7 = false;
while (!divisibleBy7) {
System.out.println(num);
if (num % 7 == 0)
divisibleBy7 = true;
--num;
}
}
}

Output:
9
8
7

Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with.


Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.

Example:

public class Myclass {
public static void main(String[] args) {
int num = 9;
boolean divisibleBy7 = false;
do {
System.out.println(num);
if (num % 7 == 0)
divisibleBy7 = true;
num--;
} while (divisibleBy7 == false);
}
}

Output:
9
8
7

For-each Loop

The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through a collection of objects, sequentially from start to finish.

The general form of the for-each version of the for loop is like

for(type count_var : collection) statement-block

The type specifies the type of the variable count_var. It receives the elements from a collection one at a time and iterates from beginning to end. With each iteration of the loop, the next element in the collection is retrieved and stored in count_var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection, the type must be the same as(or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the element type of the array.

We can also easily iterate through nested collections using the enhanced for loop.

Example:

import java.util.ArrayList;
public class Myclass {
public static void main(String[] args) {
ArrayList myList = new ArrayList();
myList.add("Java");
myList.add("Loop");
myList.add("for-each");
for (String val : myList) {
System.out.println(val);
}
}
}

Output:
Java
Loop
for-each

One thing we should consider here is, what will happen if we try to modify the loop variable in enhanced for loop?.

The answer lies in the fact that, if we are traversing through the object or primitive type. If we’re iterating through an array of primitive values, manipulation of the loop variable will never change the value of the array being iterated because the primitive values are passed by value to the loop variable in an enhanced for loop.

When we iterate through a collection of objects, the value of the collection is passed by reference to the loop variable. Therefore, if the value of the loop variable is manipulated by executing methods on it, the modified value will be reflected in the collection of objects being iterated.

Limitation of enhanced for loop

  • It can’t be used to delete or remove the elements from a collection:- The enhanced for loop hides the iterator used to iterate through the elements of a collection, we can’t use it to remove or delete the existing collection values because we can’t call the remove method.
  • We can not iterate over multiple collection arrays in the same loop.
  • The enhanced for loop can’t be used to initialize an array and modify its elements.
Follow Us On