Apps/Gaming

Java For and For-each Loops

In the Java while other do while loops programming tutorial, we learned about two of the most basic and oldest looping constructs. In today’s follow-up, we will conclude our examination of supported loop types in Java as we explore the for and for each loops.

You can learn more about while other do while loops in our guide: Java While and Do While Loops.

Java ForLoop

The Java for loop is often a better choice than a while or do while loop when you know exactly how many times you want to loop through a block of code.

the for loop syntax is considered to be somewhat more complex than that of other loop types in Java due to its use of three expressions. Here is an example of the for loop’s syntax:

for (initialExpression; testExpression; updateExpression) { // body of the loop }

In this code example:

  1. the initialExpression initializes and/or declares variables and executes only once.
  2. the testExpression condition is evaluated. If the condition is truethe body of the for loop is executed.
  3. the updateExpression updates the value of initialExpression.
  4. the testExpression condition is evaluated again. The process continues until the condition is false.

Here is a short Java program example that prints a string five times:

class ForLoopExample { public static void main(String[] args) { final int n = 5; // for loop for (int i = 1; i <= n; i++) { System.out.println("Hello world!"); } } }

When executed, the program produces the following output:

For loops can also be used to perform calculations, such as calculating the sum of natural numbers from 1 to 1000as shown in the code example below:

class ForLoopExample2 { public static void main(String[] args) { int sum = 0; final int n = 1000; for (int i = 1; i &= n; ++i) { sum += i; } System.out.println(“Sum = ” + sum); } }

Here is the output of the above program:

For loop tutorial in Java

Reading: Top Java Online Training Courses and Bundles

Beware of infinite loops

for loops are in no way immune to infinite looping, as it is possible to set the test expression in such a way that it never evaluates to falseresulting in the for loop running forever. Here is some example Java code that demonstrates an infinite for loop:

class InfiniteForLoopExample { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 10; i--) { System.out.println("Hello world!"); } } }

Here are the (partial) results, which have already exceeded the target of 10 lines:

Java for loop code examples

Reading: Java Tools to Increase Productivity

The Java For-each Loop

Added in Java 1.5, the for each loop is an alternative to the for loop that is better suited to iterating over arrays and collections. TheJava for each syntax is a whole lot simpler too; all it requires is a temporary holding variable and the iterable objects:

for (type variableName : iterableObject) { // code block to be executed }

In the following code example, a for each loop is utilized to output all elements in an array of vehicles:

thong[] cars = {“Volvo”, “BMW”, “Ford”, “Infiniti”, “Jaguar”}; for (String i : cars) { System.out.println(i); }

As you can see in the output below, each array element is accessed in order from first to last:

Java For-each loop tutorial

Developers can also use the for each loop to traverse through objects that store a collection such as a mapalthough since Java 8 the forEach() method is considered to be a better choice:

import java.util.*; class ForEachMapExample { public static void main(String[] args) { Map map = new HashMap<>(); map.put(1, “Java”); map.put(2, “is”); map.put(3, “fun!”); for (String word : map.values()) { System.out.println(“Word: ” + word); } } }

In order to be able to read the map’s values, we need to first extract them from the map. To do that, we can employ the values() method; it returns a collection of the values ​​contained in the map.

Java for each loop how to

Java continue and break in For and For-each Loops

both for other for each loops support the continue other break statements in Java. Hence, if you want to skip the current iteration, use continue:

for(int i = 0; i < 5; i++){ if (i == 2){ continue; } }

Need to break out of the whole loop? Use break:

for(int i = 0; i < 5; i++){ if (i == 2){ break; } }

To break out of more than one loop use break with a label:

outerLoop: // Label the loop for(int j = 0; j < 5; j++){ for(int i = 0; i < 5; i++){ if (i==2){ break outerLoop; } } }

A word to the wise: if you find yourself checking for a lot of specific values, it might be better to either prefilter your collection or use a separate loop for each group of values.

Final Thoughts on Java For and For-each Loops

In this Java programming tutorial, we explored the very important for other for each Java loop types. the for loop is the perfect choice when you know exactly how many times you want to loop through a block of code, while the for each loop is ideal for iterating over the elements of a simple array. Objects that store collections such as the ArrayList other HashMap provide the forEach() instance method for the looping purposes. We also discussed the use of break other continue in for other for each loops.

Reading: Java switch statements

Related posts

Smartsheet alternatives

TechLifely

LiquidPlanner Project Management Review

TechLifely

An Introduction to Thread Pools in Java

TechLifely

Leave a Comment