print
Advertisment
Advertisment

For each loop in java

Another array traversing technique is the for-each loop, the while loop, the do-while loop introduced in Java 5. It starts with the keyword just like a normal for-loop. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same as the base type of the array, followed by a colon, followed by the array name. In a for-each loop, we perform the task of printing the values one by one, like, in an array, this is typically used to iterate over an array or collection class (eg, ArrayList). In for loop, while and while we use increment-decrement but for each loop, we don't use increment-decrement. One of its good things is that it cannot traverse the elements in reverse order. Here, you don't have the option to drop any element as it doesn't work based on the index. Also, you cannot pass only odd or even elements.

Syntax


	for (datatype variablename : arrayname ){
		//statements using  
	}

Example

class Foreach{
		public static void main(String[] args) {
		 char c[] = new char[] {'a','b','c','d'};
		  for (char st : c ) {
		   	System.out.println(st);
		  }
		}         
	}

Output :


 a
 b
 c
 d
Advertisment

For each loop Example: Traversing the collection elements

import java.util.*;
class Foreach2{
	public static void main(String[] args) {
		List list = new ArrayList();
		  list.add("Red");
		  list.add("Blue");
		  list.add("Green");
		  list.add("Yellow");
			for (String s :list ) {
		    System.out.println(s);
		  }
	}
}         

Output :


	Rrd
	Blue
	Green
	Yellow
Advertisment
Advertisment
arrow_upward