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]);
}Obuolys
Kriaušė
Bananas
Apelsinas
- The array
vaisiaicontains four elements, so itslengthvalue is4. - The counter
istarts at0, the index of the first array element. vaisiai[i]accesses the next element each time, at indices0, 1, 2, 3.println()displays each fruit on a new console line.- When
ibecomes4, the condition4 < 4is false and the loop ends.
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");
}Temperatūra: 21 °C
Temperatūra: 24 °C
Temperatūra: 19 °C
Temperatūra: 27 °C
- The array
temperaturosstores four integers. - The loop uses indices in order from
0to3. - On each iteration,
temperaturos[i]returns one day's temperature. - 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ų");Bendra kaina: 14 eurų
- The array
kainosstores the values3, 4, 2, 5. - The variable
bendraKainainitially is0. - On each iteration,
kainos[i]takes the next price. bendraKaina += kainos[i]adds it to the previous sum. The sum grows as follows:3, 7, 9, 14.- 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
}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);
}Miestas: Vilnius
Miestas: Kaunas
Miestas: Klaipėda
- The array
miestaistores the names of three Lithuanian cities. - On the first iteration, the variable
miestasreceives the value Vilnius. - On subsequent iterations it receives Kaunas and Klaipėda.
for-eachstops 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]);
}Numeris 1: Asta
Numeris 2: Mantas
Numeris 3: Ona
Numeris 4: Darius
- Java's technical indices are
0, 1, 2, 3. - People usually number lists starting at
1, so we calculate the displayed number usingi + 1. - When
iis0, the user sees the number1and the first name, Asta. - 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);
}2000
4000
6000
- The initial array stores the values
2, 4, 6, representing thousands of steps. - The first
forloop accesses each element by its index. - The statement
zingsniaiTukstanciais[i] *= 1000multiplies the actual array element by a thousand. - After the first loop, the array stores the values
2000, 4000, 6000. - The second loop,
for-each, displays these updated values in the console.
Which loop should you choose?
| Task | Recommended loop |
|---|---|
| Read every element | for-each |
| Get the element index | for |
| Change an element by its position | for |
| Traverse backwards or with a different step | for |
| Sum all values | Either works |