JAVA LOOPS
Java for-each loop
for-each loop visits every element of an array or another
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
}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);
}Vaisius: Obuolys
Vaisius: Kriaušė
Vaisius: Bananas
The array vaisiaiis like a shelf with three boxes: an apple, a pear and a banana.- On the first iteration, the loop variable
vaisiusreceives the text Obuolys. - On the second iteration it receives Kriaušė, and on the third, Bananas.
- Each received value is
println()displayed on a separate console line. - 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ų");Bendra kaina: 14 eurų
- The array
kainosstores four prices:2, 3, 5, 4. - The variable
bendraKainainitially is0, because we have not added anything yet. - On each iteration, the variable
kainareceives one number from the array. - The statement
bendraKaina += kainaadds that number to the previous sum, which grows as follows:2, 5, 10, 14. - 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);
}Indeksas 0: Jonas
Indeksas 1: Ona
Indeksas 2: Rūta
Vardas: Jonas
Vardas: Ona
Vardas: Rūta
- Both loops traverse the same names array and see Jonas, Ona and Rūta.
- A regular
forhas a counter,i, so it can display both the name and its index. - Array indices start at
0, so Jonas has index 0, Ona has index 1 and Rūta has index 2. for-eachreceives each name directly, making its code shorter, but it has no index.- If you only need to read all the names, the simpler
for-eachis usually clearer.
| Requirement | Better loop |
|---|---|
| Read all elements in order | for-each |
| Use the element index | for |
| Traverse only part of an array | for |
| Traverse with a different step or backwards | for |
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]);10
- The array stores three actual values:
10, 20, 30. - On each iteration,
taskasreceives a copy of one value. - The statement
taskas *= 2doubles only this temporary copy. - The original array slot does not change, so the first element remains
10. - As a result,
System.out.println(taskai[0])displays in the console 10, not 20.
taskas receives a copy of the value.To change specific elements of an array of primitive values, use a regular for and an index.