Enhanced for each loop in Java

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable. The enhanced for loop is also called the for-each loop, and it offers some advantages over the regularfor loop. It also has some limitations.

To start with, the regular for loop is cumbersome to use when it comes to iterating through a collection or an array. You need to create a looping variable and specify the start and end positions of the collection or the array, even if you want to iterate through the complete collection or list. The enhanced for loopmakes the previously mentioned routine task quite a breeze, as the following example demonstrates for an ArrayList myList:

You can read the colon (:) in a for-each loop as “in”.

Click here to read more

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s