For Each Loops (Iteration)

Submitted by: 
Language: 

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!


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.