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
Can we override static method?
We cannot override static methods. Static methods are belogs to class, not belongs to object. Inheritance will not be applicable for class members
Famous Quotations
If you don’t make mistakes, you’re not working on hard enough problems. And that’s a big mistake.
-- Frank Wilczek

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.