FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

For-each Loops

Code Description:

A For-each loop is a unique type of loop meant for easily iterating through Arrays or Lists and to perform updates or display the values of their elements. In our example, we first create an Array to iterate through. Within the For-each loop's parenthesis, we have the data type, a temporary name for the current iteration's element, a colon, and then the Array name.

For-each Loop Syntax:

String[] array = {"element1", "element2", "element3"};
		
for (String nameForIteration : array) {

}

Runnable Foreach Loop Example Code:

public class Demo {

    public static void main(String[] args) {

	String[] statesArray = {"Alabama", "New York", "Idaho", "Florida", "New Mexico"};
		
	for (String stateString : statesArray) {
	    System.out.println(stateString);
	}

    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

For-each Loop Output Image

Important Notes:

  • Foreach loops can only be iterated through sequentially. You may not go backwards.

Related Links:

While Loops Do-While Loops For Loops Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures