Loops in Java

What are loops in Java?

A loop is a programming construct to perform an operation repeatedly several times or till it satisfies a condition.

Where do we use loops?

  • You want to display a list of records such as a list of products on a screen. Here the common operation is fetching a record and printing it on the screen.
  • You want to find a character or a sequence of characters within a text
  • You want to perform a calculation repeatedly to get to a desired result
  • You want to put a list of values by sorting them in ascending or descending order

What is an iteration in Java?

We call each repetition of a loop as an iteration. For example, if a loop repeats for 10 times, we say that it iterates for 10 times.

How many types of loops in Java?

In Java, there are basically 3 types of loops.

  • while
  • do-while
  • for

All three loops have one common thing, a condition, but written it in distinct places.

How to understand loops in Java?

The best way to understand a loop is to keep track of all the variable values or the results of operations for each iteration in a draw table. A draw table contains rows for each of the loops iteration. Each variable or operation used in that loop will be in a column.

IterationVariable 1Variable 2Operation
1
2
3

while loop

A while loop will execute a set of statements repeatedly while a condition evaluates to true.

A while loop begins with while keyword, followed by a condition within rounded parenthesis, enclosing a block of code with curly brackets.

Syntax of while loop

while (condition) {
   // Code
}

How does while loop work?

  • A while loop checks the condition first
  • Gets into the loop only if the condition is true
  • Executes the statements in the loop
  • Goes back to the condition statement again
  • Repeats above steps if condition is true
  • Goes out of the loop if condition is false

Example of while loop

package com.techstackjournal;

public class WhileLoop {
	public static void main(String[] args) {
		int factorial = 1;
		int n = 3;

		System.out.print("Factorial of " + n + " is ");

		while (n > 0) {
			factorial *= n;
			n--;
		}

		System.out.println(factorial);
	}
}
Factorial of 3 is 6
factorialnn>0factorial *= nn–
13true32
32true61
61true60
60falseNENE
NE – Not Executed

do-while Loop

A do-while loop executes a set of statements and then decides whether to repeat them again at the end of the loop.

In a do-while loop we write the condition at the end of the loop, so it will iterate the loop at least once, irrespective of whether or not it satisfies the condition. A semicolon must be placed right after do-while condition.

Syntax of do-while loop

do {
    // Code
} while (condition);

How does do-while loop work?

  • Control enters the code block directly, as there is no restriction to get inside the code block
  • Code block gets executed
  • Control flow checks the condition at the end of the loop
  • If the condition is true, the code block will be executed again
  • Goes out of the loop when condition is false

Example of do-while loop

package com.techstackjournal;

public class DoWhileLoop {
	public static void main(String[] args) {
		int factorial = 1;
		int n = 3;

		System.out.print("Factorial of " + n + " is ");

		do {
			factorial *= n;
			n--;
		} while(n>0);

		System.out.println(factorial);
	}
}
Factorial of 3 is 6
factorialnfactorial *= nn–n>0
1332true
3261true
6160false

for Loop

A for loop is another control flow structure to execute a set of statements repeatedly. Apart from the code block, it contains 3 primary sections, initialization, condition and expression.

Syntax of for loop

for(initialization; condition; expression) {
    // Code
}

Structure of for loop

All these sections are optional if needed you can keep these sections empty. However, you still need to separate these sections by commas.

for ( ; ; ) {
    // Code
}

Initialization

This is the place where variables are declared and initialized. This part is executed only once in the beginning of iterating the loop. You can declare and initialize 1 or more variables in this section separated by commas.

for(int a = 10, b = 20; ; ) { ... }

Condition Section

In this section we write the condition to check if can proceed to execute the code block or not. If condition section evaluates to true, code block gets executed, else control will come out of the for loop.

for( ; n > 0 && n < 10  ; ) { ... }

Expression Section

In this section we can write 1 or more expressions that will help in deciding the fate of the condition. If you are writing more than 1 expression, they need to be separated by a comma.

Expression section gets executed only after execution of code block and before checking the condition for the next iteration.

for( ; ; n++, m++, System.out.print(n) ) { ... }

How does for loop work?

  • Initialization section will first declare and initialize the variables
  • Then, condition section gets evaluated
  • If condition is tests true, code block will get executed
  • Expression block gets executed after it completes code block execution
  • Usually in expression section we update the variable value (which tests the condition) by an arithmetic operation, but practically we can write any expression.
  • Then, condition section gets executed again, and this cycle repeats until the condition results to false

Example of for loop

package com.techstackjournal;

public class ForLoop {
	public static void main(String[] args) {

		for (int i = 0; i < 5; i++) {
			System.out.println(i);
		}

	}
}
0
1
2
3
4
  • In the above program, first int i = 0 part will be executed. This is one-time step and will not be declared again.
  • Then, i < 5 part will be executed
  • Since, the above condition is true, it will execute the block by printing the number
  • Then, i++ part will be executed
  • After increment, i < 5 condition check part will be executed, and so on as long as the condition is true.
int i=0i<5println(i)i++
i=0true01
NEtrue12
NEtrue23
NEtrue34
NEtrue45
NEfalseNENE
NE – Not Executed

For Each Loop

A more convenient way of iterating over an Array is to use for-each loop. A for-each loop iterates once for each member of that Array. This iterate over the array without the need of the initialization, condition and incrementing, etc.

Remember that you will not be able to modify the values of these array elements. If you want that capability, you need to use the normal for-loop.

package com.techstackjournal;

public class ForEach {
	public static void main(String[] args) {

		int[] arr = { 10, 20, 30, 40, 50 };

		for (int element : arr) {
			System.out.println(element);
		}

	}
}
10
20
30
40
50

Difference between while and do-while

while Loopdo-while Loop
Condition is checked at the beginning of loopCondition is checked at the end of the loop
Control may never enter the loopControl enters the loop at least once
Doesn’t require a semi-colon to end the loopEnds with semi-colon
Entry Controlled LoopExit Controlled Loop
Syntax:
while (condition) {
// Code
}
Syntax:
do {
// Code
} while (condition);

What is the infinite loop in Java?

If a loop contains a condition that always evaluates to true, it never exits the loop, we call this situation as an infinite loop.

		int n = 0;
		while (n > 0) {
			System.out.println(n);
			n++;
		}

One should be very careful that loops are not getting into this infinite loop condition by using the right condition to exit the loop.

Sometimes, developers deliberately write an infinite loop as below and exit the loop with a break statement. Typically, we see this style of coding where menus are used.

while (true) {
  if (option == 5) {
    break;
  }
}