Java For Loop

In this lesson, we will explore the for loop in Java.  But first, let’s see what loops are in general.

What are loops in Java?

We use loops to execute a certain block of code or just one statement a controlled number of times.

The value of the logical expression controls the number of repetitions of a particular code block in loops. This means that the statement or the code block would be repeated as long as the value of that logical expression is equal to true, and it will stop the moment the value of that logical expression becomes false.

There are three types of loops in Java:

In this tutorial, we will cover Java for loop.

Java For Loop

Java for loop is used to run a block of code several times.

The syntax is:

 for (value initialization; testing expression; updating the value) {
    // body of the loop
 }


The flow of the for loop

java for loop

 

Here, the value’s initialization runs first, which gets executed only once.  After that, the condition gets evaluated. If the condition is true, the for loop’s body gets executed, the value gets updated, and this process is repeated until the condition becomes false.

Let’s look at an example:

class Test {
    
  public static void main(String[] args) {
    // count value exactly 5 times
    for(int i = 1; i<=5; i++) {
      System.out.println("Count: " + i);
    }
  }
}
Output: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
 
Here, we printed the value precisely 5 times. We first initialized the value of the variable i to 1, then started executing the block of code in a loop until the variable’s value was greater than 5. Then the condition became false, and the iteration stopped.

Let’s see how we can iterate through the array and print out all the elements:

class Test {
    
  public static void main(String[] args) {
    String[] names = {"John", "Steve", "Mellisa", "Megan", "Ryan"};
        
    for (int i = 0; i < names.length; i++) {
      System.out.print(names[i] + " ");
    }
  }
}
Output: John Steve Mellisa Megan Ryan
 
Here, we iterated through the array, starting from index 0, until the value i became equal to the length of the array, which is 5.

Java for-each loop

The for-each is a type of a for loop that is a little easier to use. It is most commonly used to iterate through an array or some collection elements.

Example of the for-each loop:

class Test {
    
  public static void main(String[] args) {
    String[] names = {"John", "Steve", "Mellisa", "Megan", "Ryan"};
        
    for (String name : names) {
      System.out.print(name + " ");
    }
  }
}
Output: John Steve Mellisa Megan Ryan
 
You can see that the for-each loop is a bit easier to write than the regular for loop.

Nested For loops

We can also have one for loop inside another:

class Test {
    
  public static void main(String[] args) {
    String[] names = {"John", "Steve"};
    int[] numbers = {1, 2, 3};
        
    for (int i = 0; i < names.length; i++) {
      for (int j = 0; j < names.length; j++) {
        System.out.println(names[i] + ": " + numbers[j]);
      }
    }
  }
}
Output: John: 1 John: 2 Steve: 1 Steve: 2

Java forEach method

Since Java 8, we have a new forEach method that we can use instead of a loop.

Example of Java 8 forEach method:

class Test {
    
  public static void main(String[] args) {
    List<String> names = new ArrayList<>();
    names.add("Steve");
    names.add("Megan");
    names.add("Ryan");
    names.add("Melissa");
        
    names.forEach(name -> System.out.println(name));
  }
}
Output: Steve Megan Ryan Melissa
 
In the example above, we used a list instead of an array. In later tutorials, you will learn how to work with lists and other types of collections in Java.

Here we took advantage of the new forEach loop that accepts the Consumer interface as a parameter. The Consumer interface is a functional interface (an interface with a single abstract method). It accepts an input and returns no result.

Java Infinite For Loop

If we set the test expression so that it never evaluates to false, the for loop will run forever. This is called an infinite for loop.

Example of infinite for loop:

class Test {
    
  public static void main(String[] args) {
    for (int i = 5; i >= 0; i++) {
      System.out.println("Print something...");
    }
        
  }
}

Here, we initialize the variable’s value to 5 and iterate as long as that value is greater than 5, which means until memory runs out.

That’s it!

Leave a Reply

Your email address will not be published.