JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Checkout for Promo Codes

Java For each Loop


The basic for loop was extended in Java 5 to make iteration over arrays and other collections more easy. This newer for statement is called the enhanced for or for-each. The for-each loop is used to access each successive value in a collection of values. The main usage of for each is iterating over collection classes or arrays. Here is the syntax to use for each loop:

for (data_type item: iterable_collection or array) {
       // do something to item
}

Here is an example for for each loop:

package com.java2novice.loops;

import java.util.ArrayList;
import java.util.List;

public class SimpleForEachEx {

	public static void main(String a[]){
		List<String> al = new ArrayList<String>();
		al.add("java2novice");
		al.add("for each");
		al.add("java 1.5");
		al.add("www.java2novice.com");
		/**
		 * during each iteration, the object in the sequence 
		 * will be assigned to string reference str.
		 */
		for(String str:al){
			System.out.println(str);
		}
	}
}

Output:
java2novice
for each
java 1.5
www.java2novice.com
<< Previous Program | Next Program >>

Java Loop Examples

  1. Java While Loop
  2. Java Do-While Loop
  3. Java For Loop
  4. Java For each Loop
  5. break statement in java
  6. continue statement in java
Knowledge Centre
Purpose of garbage collection
The garbage collection process is to identify the objects which are no longer referenced or needed by a program so that their resources can be reclaimed and reused. These identified objects will be discarded.
Famous Quotations
It is easier to fight for one’s principles than to live up to them.
-- Alfred Adler

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2020 by Nataraja Gootooru. All Rights Reserved.