java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to use for-each in Java?

Using for-each like command to iterate arrays or a list can be much simplified our code. Below is an example how to do it in Java, the first loop is for iterating array and the second for iterating a list containing a some names.

package com.javacoderanch.example.lang;

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

public class ForEachExample {
	public static void main(String[] args) {
		Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};
		
		for (Integer i : numbers) {
			System.out.println("Number: " + i);
		}
		
		List<String> names = new ArrayList<String>();
		names.add("James");
		names.add("Joshua");
		names.add("Scott");
		
		for (String name : names) {
			System.out.println("Name: " + name);
		}
	}
}