Core Java

Java Loops Tutorial

Java Loops provide a means to perform a particular task repeatedly. In this article, we shall discuss about the loops in Java and their usage.

1. While loop

The while statement continually executes a block of statements until a particular condition is true.

while (expression){
    statements
}

A while loop contains an expression, which when evaluates to true, would execute the embedded block of statements. The while loop continues testing the expression and executing its block until the expression evaluates to false. Let us look at an example for while loop.

whileDemo.java

public class whileDemo {
	public static void main(String args[]){
		System.out.println("A while test");
		int count=1;
		while(count<=5){
			System.out.println("while iteration :"+count);
			count++;
		}
	}
}
A while test
while iteration :1
while iteration :2
while iteration :3
while iteration :4
while iteration :5

Use a while loop when you have to evaluate a block of statements repeatedly based on an expression/ condition. Do note that the loop may run infinitely if the expression always evaluates to true.

2. Do-while loop

A do-while statement is similar to the while loop, with the only difference being that a do-while statement evaluates the expression at the end of the loop instead of the top.

do {
    statements
} while (expression);

You would notice that the block of statements inside the do-while loop will get executed at least once irrespective of whether the expression evaluates to true or false.

doWhileDemo.java

public class doWhileDemo{
	public static void main(String args[]){
		System.out.println("A do-while test");
		int count=1;
		do{
			System.out.println("do-while iteration count:"+count);
			count++;
		}while(count<=5);
	}
}
A do-while test
do-while iteration count:1
do-while iteration count:2
do-while iteration count:3
do-while iteration count:4
do-while iteration count:5

Use a do-while loop if you want to execute a block of statements at least once and then repeat until the expression evaluates to false. Similar to while loop, the statements may get executed infinitely if the expression always evaluates to true

3. For loop

The for statement provides a compact way to iterate over a range of values. Use a for loop to iterate through a range of values in a collection. The different flavors of for loop iterations are

  • simple for loop
  • for each loop
  • Java 8 foreach

3.1 Simple for loop

The general form of a simple for statement can be expressed as follows.

for(initialization; termination; increment){
   statements
}

This version of for loop contains:

  • initialization expression initializes the loop. It is executed once as the loop begins
  • termination expression terminates the loop when it evaluates to false
  • increment expression is invoked after each iteration to increment or decrement a value

Let us look at an example of a simple for loop

forDemo.java

public class forDemo {
	public static void main(String args[]){
		System.out.println("A simple for loop test");
		for(int count=1;count<=5;count++){
			System.out.println("for iteration count:"+count);
		}
	}
}
A simple for loop test
for iteration count:1
for iteration count:2
for iteration count:3
for iteration count:4
for iteration count:5

3.2 For each loop

The enhanced for loop is mainly for iteration through Collections and Arrays. It makes the loop more compact and easy to read. The general form of the for-each construct can be expressed as below.

for( Object ob  : <Collection to traverse> ){
   statements
}

The Object can be any primitive or object type (String, List or a custom object type like Person). The colon (:) should be read as “in”. In the below example the construct should be read as “for each int num in intArray“. Let us see an example to iterate through an array

EnhanceForDemo.java

public class EnhanceForDemo {
	public static void main(String args[]){
		System.out.println("Java5 for each test");
		int intArray[] = {1,2,3,4,5};
		for (int num : intArray){
			System.out.println("the number in array:"+num);
		}
	}
}
Java5 for each test
the number in array:1
the number in array:2
the number in array:3
the number in array:4
the number in array:5

The for-each construct combines beautifully with generics. The compiler does the iterator declaration and hence doesn’t need to be explicitly stated. But the for-each construct cannot be used everywhere. As the for-each construct hides the iterator, it cannot be used to filter or remove an element. It also cannot be used for loops that must iterate through multiple collections in parallel.

3.3 Java 8 foreach loop

Java8 introduced new forEach method in Iterable to loop through elements in a collection. The method default void forEach(Consumer<? super T> action) performs a given action for each element of the Iterable until all elements have been processed or the action throws an exception.

The forEach method can be expressed as <CollectionObject>.forEach(<action to be performed for each iteration>). Let us look at an example.

Java8forEachDemo.java

import java.util.Arrays;
import java.util.List;

public class Java8forEachDemo {
	public static void main(String args[]){
		System.out.println("A Java 8 forEach test:::");
		List Team = Arrays.asList("Mark","Jerry","Robin","Mike");
		Team.forEach(name -> System.out.println(name));
		// the above can also be written using stream. Lets sort it too.
		System.out.println("lets try again with stream and sort:::");
		Team.stream().sorted().forEach(System.out::println);
	}
}
A Java 8 forEach test:::
Mark
Jerry
Robin
Mike
lets try again with stream and sort:::
Jerry
Mark
Mike
Robin

4. Download the Source Code

Download
You can download the full source code of this example here: Java Loops Tutorial

Venkat-Raman Nagarajan

Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button