Loops in Java [ For, While & Do While ] with Examples

Loops are an important tool used in programming languages in order to execute a set of functions again and again after some expressions become true. The main types of loops [ while & do while ] used in Java.

Loops in Java

A for loop is used to provide a short and easy way to debug the stricter of the loop in Java. It writes the structure of the loop in a concise was and checks the condition in one line. Java for loop is further divided into three types. They are:

  1. For loop 

It is a control flow statement that gives a short and easy way to debug the stricter of the loop in Java. It iterates a part of the programs many times and it is recommended to be used in the situation in which the number of iteration is fixed.

The structure of the loop through this loop is concise and this type of loop performs the initialization, condition, and increment in a single line. Therefore, this loop saves the time of debugging the structure of the loop.

syntax:

for(<initialization>;<loop condition>;<increment/decrement expression>){
//executable statements }

For loop is a looping construct that executes a set of instructions specified number of times.

Example:

public class ForLoopDemo {

	public static void main(String[] args) {

		for (int i = 0; i < 10; i++) {
			System.out.println("Value of i is : " + i);
		}
	}
}
  • Initialization condition

It is the initial condition in which the variables in use are initialized. It is executed when the loop starts and it marks the beginning of the loop. The users can either use a new variable or an already declared variable.

  • Testing condition

It is the second condition that tests the exit condition for a loop. It is executed every time in order to check the condition of the loop and it must always return value in the form of either a true or a false. It continues to be executed until the condition is false.

  • Statement execution

The statement of the loop continues to get run when the second condition continues to be true.

  • Increment/Decrement

It is used to either increase or decreases the variable for the next iteration.

  • Loop termination

In the case in which, the second condition returns a false value, the loop gets termination and ends its life cycle.

For loop is divided into four types:

1. simple for loop

Simple for loop is the same as for loop that is described above. It initiates the variables and tests condition. The value of the variable is increased or decreased in the same way as well.

Example:

class SimpleLoop  {

  public static void main (String args[]) {
  
    for (int i = 1; i <= 10; i = i + 1) {  
      System.out.println(i);
    } 
    System.out.println("Java World");

  }

}

2. for each loop

for each loop traverses an array or set in Java. It uses subscript notation and does not require the increment value which makes this loop more convenient to use than the simple for loop. It does not function on the basis of the index but rather works on the basis of the element. This loop returns a single element at one time in the defined variable.

Example:

package com.javafolder.loops.example;

import java.util.*;

public class ForEachDemo {

	public static void main(String args[]) {

		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(10);
		list.add(20);
		list.add(30);
		list.add(40);
		list.add(50);
		list.add(60);
		list.add(70);
		list.add(80);
		list.add(90);
		list.add(100);

		for (Integer s : list) {
			System.out.println("Value of s : "+ s);
		}
	}
}

3. labeled for loop

This loop is a type of for loop that has been named and is used to perform a specific function. Such labeled loop is mostly used when the users have nested for loop so that the loop can be continued or broke in particular conditions.

Example:

public class LabeledForLoop {

	public static void main(String[] args) {

		int number = 0;

		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 5; j++) {
				if (i == 5)
					break;
			}
			number++;
		}

		System.out.println(number);
	}
}

4. infinitive for loop

This loop is created when the users use two semicolons in the for the loop.

public class InfinitiveLoop {  
public static void main(String[] args) {  
    
    for(;;){  
        System.out.println("infinitive loop");  
    }  
}  
}

2. While Loop

While loop is defined as a control flow statement that allows the code to be run continually on the basis of the provided Boolean condition. This loop is recommended to be used in the case in which the number of the iteration is not fixed. It first checks the Boolean condition and if the condition is found to be true, then the body statement of the loop is run.

If the condition is found to be false, then only the first statement following the loop is run.  Then the loop gets terminated and ends its lifecycle. In the situation in which the users pass true in the while loop, then such while loop becomes an infinitive while loop.

Syntax:

while<loop condition>
//statements

public class WhileLoopDemo {

	public static void main(String[] args) {

		int number = 0;

		while (number < 10) {
			number++;

			System.out.println(number);

		}

	}
}

 3. Do While Loop

It is a control flow statement that is used to iterate a part of the program multiple times. It is recommended to use the do-while loop in the case in which it is required to run the loop at least a single time and the number of iteration is also not fixed.

This loop first executes the statement before checking the condition to be true or false. Therefore, the statement gets executed at least once in this type of loop.

public class DoWhileDemo {

	public static void main(String[] args) {

		int a = 1;
		int b = 2;
		int x = a + b;
		do {
			System.out.println(x);
			x++;
		} while
		(x <= 10);
	}
}

After executing the statement, it checks the Boolean condition. In case of the condition being true, the next iteration of the loop begins and in the case of the condition being false, the loop gets termination and ends its life cycle.

Java Infinite do-while Loop

If a statement is passed as true in a do-while loop, the loop will become an infinite do-while loop.

Example:

package Collection;

public class InfiniteDoWhileLoop {

	public static void main(String[] args) {
		do {
			System.out.println("I am always looping...");

		} while (true);
	}
}

In the situation in which the users pass true in the do-while loop, then such a do-while loop will become an infinitive do-while loop.

Leave a Reply

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