Java foreach loop: Explained with 2 examples

The Foreach loop in Java

A few main points about the foreach loop:

  • The foreach loop was introduced in JDK 1.5.
  • The foreach loop enables to traverse through the arrays sequentially, without using the index variable.
  • The foreach is often used in arrays.
  • The foreach loop is not used like in other programming languages by using the “each” keyword. It is just like the for loop but acts like the “foreach”, See the examples below.

Example of using Java foreach loop

The following example uses the split method of Java string and breaks a string completely by a regular expression. The example uses foreach Java loop to display array items created after the split method.

Java foreach loop

Experience this online

The output will be:

name is: Mike

age is: 30

salary is: $5000

A foreach loop example with an array

This example declares an array with five elements and then displays “each” array element by using the foreach loop.

Experience this online

The output will be:






Also see: for loop

Was this article helpful?

Related Articles

Leave A Comment?