JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

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
What is race condition?
A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.
Famous Quotations
There is a great difference between worry and concern. A worried person sees a problem, and a concerned person solves a problem.
-- Harold Stephens

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 © 2022 by Nataraja Gootooru. All Rights Reserved.