Foreach loops

Intermediate Java

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

Intermediate Java

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

Intermediate Java

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
Intermediate Java

Let's practice!

Intermediate Java

Preparing Video For Download...