Foreach loops

Java für Fortgeschrittene

Jim White

Java Developer

foreach

  • Allows iterating through things like arrays without managing indexes
  • Useful when we don't need to know where the value is

Spiral arrow

Java für Fortgeschrittene

foreach syntax

String[] names = {"Ada", "Ivo", "Ti"}

for (String name: names){
  System.out.println(name);
}
Ada
Ivo
Ti
  • name: temporary variable, needs to have a type
  • names: array (or generally an iterable)

 

On each iteration, Java automatically gives us the next element of the iterable

 

For each name in names, do something

Java für Fortgeschrittene

for each loop

Pros

  • Improves readability over normal for loop
  • Removes extra setup

 

  • Better for:
    • Working with values as they are
      • E.g., printing the values

Cons

  • Not working with indexes
  • Can only use the value we get

 

  • Bad for:
    • Changing values
    • Keeping track of position
Java für Fortgeschrittene

Let's practice!

Java für Fortgeschrittene

Preparing Video For Download...