Skip to main content

For Each Loops (Iteration)


Introduction:
Welcome, this page will teach you how to create a For Each Loop in Java.

What is a For Each Loop?
A For Loop is very similar to a For Loop within Java except it only requires two arguments and instead of referring to the current value of the loop through the index, we have an actual item.

When are For Each Loops used?
For Each Loops are used for iterating through a list of values or items and performing an action on each of them individually. For example; if you wanted to change the boolean "active" of each item to true.

Why not just use a For Loop?
For Each Loops make it slightly easier to iterate through a list of values or items as it gives us an actual item to use as a reference, instead of just an index id or integer to be used. For Each Loops tend to be used for iterating through actual lists or arrays in Java, whereas For Loops tend to just be used for performing actions with a row of different integers.

Examples:
Here is an example of an Array of String items which is looped through using a For Each Loop to output each String to the console...

  1. String[] test = new String[]{"Hello", "Hey", "Hi"};
  2. for (String value : test) {
  3. System.out.println(value);
  4. }

Which gives the output:

Hello
Hey
Hi

Please Note:
You are able to also use a version of indexing while using it as a For Each Loop. This only works for ArrayLists (as opposed to arrays) and can be achieved through:

  1. ArrayList<String> test2 = new ArrayList<String>();
  2. test2.add("hi");
  3. test2.add("hey");
  4. test2.add("hello");
  5. for(Iterator<String> i = test2.iterator(); i.hasNext(); ) {
  6. String item = i.next();
  7. System.out.println(item);
  8. }

Finished!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.