JAVA LOOPS

Java for-each loop

for-each loop visits every element of an array or another in order. It needs neither a separate counter nor an element index.

When is for-each used?

This loop is suitable when you need to read every element of a dataset in order and its position does not matter. Its shorter syntax often makes the code clearer than a regular for with the condition i < masyvas.length.

for-each syntax

for (elementoTipas elementas : duomenuRinkinys) {
    // This code runs for each element
}
This syntax template produces no console output.

It simply shows where to put the actual element type, its name and the dataset.

  • The element type must match the type of values stored in the dataset.
  • The element variable receives the next value from the dataset on each iteration.
  • The dataset can be an array or, for example, a Java collection.
  • The symbol : is read as “for each element in the dataset”.

Traversing a string array

We have three fruits. The for-each loop takes them one at a time and displays them in the console:

String[] vaisiai = {"Obuolys", "Kriaušė", "Bananas"};

for (String vaisius : vaisiai) {
    System.out.println("Vaisius: " + vaisius);
}
Console output

Vaisius: Obuolys
Vaisius: Kriaušė
Vaisius: Bananas

  1. vaisiai is like a shelf with three boxes: an apple, a pear and a banana.
  2. On the first iteration, the loop variable vaisius receives the text Obuolys.
  3. On the second iteration it receives Kriaušė, and on the third, Bananas.
  4. Each received value is println() displayed on a separate console line.
  5. After the last fruit, the loop ends automatically. We do not need to increment a counter ourselves.

Processing numbers

Jonas bought four simple products. Their prices can be added using for-each:

int[] kainos = {2, 3, 5, 4};
int bendraKaina = 0;

for (int kaina : kainos) {
    bendraKaina += kaina;
}

System.out.println("Bendra kaina: " + bendraKaina + " eurų");
Console output

Bendra kaina: 14 eurų

  1. The array kainos stores four prices: 2, 3, 5, 4.
  2. The variable bendraKaina initially is 0, because we have not added anything yet.
  3. On each iteration, the variable kaina receives one number from the array.
  4. The statement bendraKaina += kaina adds that number to the previous sum, which grows as follows: 2, 5, 10, 14.
  5. Once the loop ends, the console displays the final sum: 14 eurų.

Comparing for and for-each

String[] vardai = {"Jonas", "Ona", "Rūta"};

// Standard for: we have an index
for (int i = 0; i < vardai.length; i++) {
    System.out.println("Indeksas " + i + ": " + vardai[i]);
}

// for-each: we get the element directly
for (String vardas : vardai) {
    System.out.println("Vardas: " + vardas);
}
Console output

Indeksas 0: Jonas
Indeksas 1: Ona
Indeksas 2: Rūta
Vardas: Jonas
Vardas: Ona
Vardas: Rūta

  1. Both loops traverse the same names array and see Jonas, Ona and Rūta.
  2. A regular for has a counter, i, so it can display both the name and its index.
  3. Array indices start at 0, so Jonas has index 0, Ona has index 1 and Rūta has index 2.
  4. for-each receives each name directly, making its code shorter, but it has no index.
  5. If you only need to read all the names, the simpler for-each is usually clearer.
Choosing between a regular for and for-each
RequirementBetter loop
Read all elements in orderfor-each
Use the element indexfor
Traverse only part of an arrayfor
Traverse with a different step or backwardsfor

Important for-each limitations

for-each does not directly provide the current element's index. Also, assigning a new value to a primitive loop variable does not change the array element itself:

int[] taskai = {10, 20, 30};

for (int taskas : taskai) {
    taskas *= 2;
}

System.out.println(taskai[0]);
Console output

10

  1. The array stores three actual values: 10, 20, 30.
  2. On each iteration, taskas receives a copy of one value.
  3. The statement taskas *= 2 doubles only this temporary copy.
  4. The original array slot does not change, so the first element remains 10.
  5. As a result, System.out.println(taskai[0]) displays in the console 10, not 20.
The loop variable taskas receives a copy of the value.

To change specific elements of an array of primitive values, use a regular for and an index.