Loops

The real power of computers is repetition. Java loops are similar to C++ and other languages.


Count while repeating (for)

for (int i = 0; i < 10; i++) {
    System.out.println("Repeating: " + i);
}

Translation:

(Start i at 0; while i is less than 10; increase i by 1) repeat {
    print "Repeating: " plus i and move to the next line;
}

Pull items from a bundle (enhanced for-each)

This is a convenient way to take items out of a list.

ArrayList<String> foods = new ArrayList<>();
foods.add("chicken");
foods.add("pizza");

for (String food : foods) {
    System.out.println(food + " sounds delicious!");
}

Translation:

Create a bundle called foods;
Put chicken into foods;
Put pizza into foods;

Repeat by taking each item from foods and naming it food {
    print food plus " sounds delicious!";
}

Repeat while a condition is true (while)

int energy = 3;

while (energy > 0) {
    System.out.println("Energy left: " + energy);
    energy = energy - 1;
}

Translation:

While (energy is greater than 0) repeat {
    print "Energy left: " plus energy and move to the next line;
    subtract 1 from energy;
}

Use Java’s tireless repetition power well.