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

Loop Through An Array

Loop Through an Array

You can traverse through the elements of an array using a for loop, leveraging the length property to determine the iteration count.

The subsequent example prints out all elements within the “cars” array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}

Loop Through an Array with For-Each

Additionally, there exists a “for-each” loop, designed specifically for iterating through elements within arrays:

Syntax

for (type variable : arrayname) {
  ...
}

Below is an example that displays all elements in the “cars” array by employing a “for-each” loop.

Example

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

The example mentioned can be interpreted as follows: for every String element (referred to as “i” for index) within the “cars” array, print the value of “i”.

When comparing the for loop and the for-each loop, it’s evident that the for-each approach is simpler to write. It eliminates the need for a counter (using the length property) and enhances readability.