CODE STRUCTURE

Traversing Java arrays with loops

Loops let you process each array element in order. A regular for provides the element index, while for-each lets you work directly with the values.

Traversing an array with for

The counter starts at 0 because that is the first element's index. The condition uses length, so the loop stops before reaching an index that does not exist.

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

for (int i = 0; i < vaisiai.length; i++) {
    System.out.println(vaisiai[i]);
}
Console output

Obuolys
Kriaušė
Bananas
Apelsinas

  1. The array vaisiai contains four elements, so its length value is 4.
  2. The counter i starts at 0, the index of the first array element.
  3. vaisiai[i] accesses the next element each time, at indices 0, 1, 2, 3.
  4. println() displays each fruit on a new console line.
  5. When i becomes 4, the condition 4 < 4 is false and the loop ends.
Use the condition i < masyvas.length.

The last element's index is length - 1, so the operator <= would cause an index out-of-bounds error.

Reading numeric elements

The same loop structure can display temperatures for four days:

int[] temperaturos = {21, 24, 19, 27};

for (int i = 0; i < temperaturos.length; i++) {
    System.out.println("Temperatūra: " + temperaturos[i] + " °C");
}
Console output

Temperatūra: 21 °C
Temperatūra: 24 °C
Temperatūra: 19 °C
Temperatūra: 27 °C

  1. The array temperaturos stores four integers.
  2. The loop uses indices in order from 0 to 3.
  3. On each iteration, temperaturos[i] returns one day's temperature.
  4. Java joins the text, number and character °C, then displays the full line in the console.

Calculating the sum of array elements

Jonas has four purchases. A variable outside the loop can accumulate their total price:

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

for (int i = 0; i < kainos.length; i++) {
    bendraKaina += kainos[i];
}

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

Bendra kaina: 14 eurų

  1. The array kainos stores the values 3, 4, 2, 5.
  2. The variable bendraKaina initially is 0.
  3. On each iteration, kainos[i] takes the next price.
  4. bendraKaina += kainos[i] adds it to the previous sum. The sum grows as follows: 3, 7, 9, 14.
  5. When the loop ends, the console displays the final sum, 14 eurų.

Traversing an array with for-each

When you only need element values, you can omit the counter and index:

for (elementoTipas elementas : masyvas) {
    // Action on the element
}
This syntax template produces no console output.

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

The colon can be read as “for each element in the array”:

String[] miestai = {"Vilnius", "Kaunas", "Klaipėda"};

for (String miestas : miestai) {
    System.out.println("Miestas: " + miestas);
}
Console output

Miestas: Vilnius
Miestas: Kaunas
Miestas: Klaipėda

  1. The array miestai stores the names of three Lithuanian cities.
  2. On the first iteration, the variable miestas receives the value Vilnius.
  3. On subsequent iterations it receives Kaunas and Klaipėda.
  4. for-each stops automatically after the last element, so no index or update is needed: length.

When you need the element index

for-each does not provide the current position. To display a position number or otherwise use the index, choose a regular for:

String[] vardai = {"Asta", "Mantas", "Ona", "Darius"};

for (int i = 0; i < vardai.length; i++) {
    System.out.println("Numeris " + (i + 1) + ": " + vardai[i]);
}
Console output

Numeris 1: Asta
Numeris 2: Mantas
Numeris 3: Ona
Numeris 4: Darius

  1. Java's technical indices are 0, 1, 2, 3.
  2. People usually number lists starting at 1, so we calculate the displayed number using i + 1.
  3. When i is 0, the user sees the number 1 and the first name, Asta.
  4. This lets us use both an element's position and its value.

Changing array elements in a loop

Step counts for three days are recorded in thousands. To convert them into actual counts, we need their indices:

int[] zingsniaiTukstanciais = {2, 4, 6};

for (int i = 0; i < zingsniaiTukstanciais.length; i++) {
    zingsniaiTukstanciais[i] *= 1000;
}

for (int zingsniai : zingsniaiTukstanciais) {
    System.out.println(zingsniai);
}
Console output

2000
4000
6000

  1. The initial array stores the values 2, 4, 6, representing thousands of steps.
  2. The first for loop accesses each element by its index.
  3. The statement zingsniaiTukstanciais[i] *= 1000 multiplies the actual array element by a thousand.
  4. After the first loop, the array stores the values 2000, 4000, 6000.
  5. The second loop, for-each, displays these updated values in the console.

Which loop should you choose?

Using for and for-each with arrays
TaskRecommended loop
Read every elementfor-each
Get the element indexfor
Change an element by its positionfor
Traverse backwards or with a different stepfor
Sum all valuesEither works