Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

For Each Loop

For-Each Loop

Additionally, there exists a “for-each” loop designed specifically for iterating through elements within an array.

Syntax

for (type variableName : arrayName) {
  // code block to be executed
}

Using a “for-each” loop, the following example prints out all elements in the cars array.

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

 

Note: If the example above seems confusing, don’t worry. You’ll learn more about arrays in the Java Arrays chapter.