Introduction to Java Loops

Introduction to Java Loops

Looping through an array or a collection is a very common day to day activity, in this post, we will get an introduction to Java Loops. We will be exploring various options for looping using Java.

 

Introduction

Looping is a feature which allows us to execute through a set of statements until our condition expression evaluates to false. Java provides multiple ways to Loop and choice is dependent upon the particular use case where we want to use it.

On a high level here are the options for Java Loops.

  1. for Loop
  2. While Loop
  3. Do-While Loop
  4. Enhanced for-each Loop

 

1. for Loop

A simple for loop which allows us to iterate over items until a specified condition is met or satisfied. This normally works with the help of a counter which will be initialized at the start of the execution and will be incremented with each iteration.

Based on the Java doc definition, a simple for loop have the following syntax

for (initialization; termination;increment) {
    statement(s)
}

Here are some of the important point to keep in mind while using simply for loop

  1. initialization will be done only once at the beginning of the loop.
  2. Loop will terminate when the termination condition will be evaluated as true.
  3. The increment is evaluated/ processed at each iteration.

 

Here is a very simple example

public class ForLoops {

    public static void main(String[] args) {

        for(int i=0 ;i<=6 ; i++){

            System.out.println("Value of i =" +i);
        }
    }
  
}

Output

Value of i =0
Value of i =1
Value of i =2
Value of i =3
Value of i =4
Value of i =5
Value of i =6

All three expressions for the for loop are optional which means you can easily create an infinite loop by removing all these expressions.

public class InfiniteForLoop {

    public static void main(String[] args) {

        //infinite loop by removing all expressions
        for(; ; ){

            System.out.println("Infinite Loop");
        }
    }
}

 

2. While Loop

As the name suggests, While loop will continually process statement or given code block while it’s evaluation expression is true.Here is an expression for while loop as per Java docs.

while (expression) {
    statement(s)
}

Here is a sample programme

public class WhileLoop {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {
            System.out.println("Value of i = " + i);
            i++;
        }
    }
}

You can implement infinite while loop by setting expression as true 

public class WhileLoop {

    public static void main(String[] args) {
        while (true) {
          //your work
        }
    }
}

 

 

3. Do-While Loop

The do-while and while loop is similar and work in a similar way except that in a do-while loop, an expression is evaluated at the bottom as compared to the while loop.To put in another way, do block are always executed at least once.

public class DoWhileLoop {

    public static void main(String[] args) {

        int i = 0;
        do {
            System.out.println("Value of i = " + i);
            i++;
        } while (i < 5);
    }
}

 

4. Enhanced for Loop

Java 5 introduced a variation of the for loop known as enhanced for-loop.It provides a simple way to iterate over the elements of array/collection.Here is a syntax for the enhanced for loop

for(Type item : items){
    //Business rules
}

In order to use this loop, we only need to define following 2 things

  1. Type to hold element being iterated.
  2. Source of the iteration

We are no longer required to declare iteration index to loop through the element as this will be taken care internally by JDK. Here is an example demonstrating difference between simple for loop and enhanced for loop in Java

public class EnhancedForLoop {

    public static void main(String[] args) {
        
        List<String> stringList= Arrays.asList("One", "Two","Three");
        
        //in old for loop
        for(int i =0 ; i<= stringList.size() ; i++){
            System.out.println("List Value is "+stringList.get(i));
        }
        
        //with enhanced for loop
        for(String value : stringList){
            System.out.println("List Value is "+value);
        }
    }
}

 

4.1 Iterable.forEach()

We are already into Java 9 and it will not be good if we do not cover new enhancement introduced in Java 8.We have now a default method named forEach() added to the java.lang.Iterable<T> interface with an ability to accept lambda expressions.

Let’s take our earlier example and see how this can be redefined by utilizing new Java 8 feature

public class ForEachJava8 {

    public static void main(String[] args) {

        List<String> stringList= Arrays.asList("One", "Two","Three", "Four");

        //Before Java 8

        for(String value : stringList){

            //work will be done here
        }

        // With Java 8 and Lambda Expressions

        stringList.forEach(name -> System.out.println(name));

    }
}

As we saw, with introduction of Lambda Expression in Java 8, we were able to iterate through element using a single line of code

stringList.forEach(name -> System.out.println(name));

I will be covering benefits of Lambda and parallel execution in some other post.Read our article Lambda Expressions in Java to start with Java 8 Lambda Expressions.

Summary

In this post, we discussed different Java Loops. We covered new enhancement introduced in Java 5 for enhanced for loop along with the new features introduced with Java 8. You can download the examples from Github

Comments are closed.

Scroll to Top