For-Each Loop in Java

FacebooktwittertumblrFacebooktwittertumblr

Hi! This is one of the articles from our Java Tutorial for Beginners.

Have you ever used loops in programming?


The "For-Each" Loop:

  • is a version of the "for" loop.
  • is used to check whether each element in an array or in a collection matches some condition.
  • appeared for the first time in JDK5

Let's examine how the syntax of the "For" loop and the syntax of the "For-Each" loop appear.

1. The Syntax of the "For" Loop

2. The Syntax of the "For-Each" Loop

Note: In the "For-Each" loop, the type item must match the type item of the array.

In order to understand how the two loops differ, let's solve the same task two different ways:

  1. With the help of the "for" loop
  2. With the help of the "for-each" loop

Task No. 1

It's necessary to check whether each element in the array matches the condition, and then to display the ones that match the condition in the console.

1. "For" Loop Solution:

If you run this code, you will see the following in the console:

51
136
387

 

2."For-Each" Loop Solution:

If you run this code, you will see the following in the console:

51
136
387

As you see, the "for-each" loop does not require you to manually change the variable. The loop automatically executes this job.

Note: In the "For-Each" loop, the type item must match the type item of the array.

In the previous example, our array has the "int" type item. That's why we wrote the following:

Task No. 2

It's necessary to check whether each element in the array matches the condition.

1. "For"Loop Solution:

If you run this code, you will see the following in the console:

51
136
387

2. "For-Each" Loop Solution:

If you run this code, you will see the following in the console:

51
136
387

As you see, the "for-each" loop does not require you to manually change the variable. The loop automatically executes this job.

So, the "for-each" loop is very convenient when it's necessary to:

  • display all the values of elements of an array/collection in the console
  • or copy all the values of elements in one array/collection and put them in a different array/collection.

You can find more articles in our Java Tutorial for Beginners. 

FacebooktwittertumblrFacebooktwittertumblr

FacebooktwittertumblrFacebooktwittertumblr
Самоучители--узнать детальнее--