Enhanced For Loop
Part of the Fundamentals section of Coddy's Java journey — lesson 65 of 73.
The enhanced for loop, also known as the for-each loop, provides a simpler way to iterate through arrays and collections. It automatically handles the indexing and retrieval of elements, making the code more readable and less prone to errors.
Here's the basic syntax of an enhanced for loop:
for (data_type element : array_or_collection) {
// Code to be executed for each element
}data_type: The type of elements in the array or collection.element: A variable that will hold the current element in each iteration.array_or_collection: The array or collection you want to iterate over.
Here's an example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}In this example, the loop iterates over the numbers array. In each iteration, the current element is assigned to the number variable, and the code inside the loop is executed. The output will be:
1
2
3
4
5The enhanced for loop is especially useful when you need to access each element in a collection without modifying the collection itself. It simplifies the code and makes it more readable.
Challenge
EasyCreate a program that does the following:
- Initializes an array of strings named
fruitswith the values"apple","banana","orange","grape", and"kiwi". - Uses an enhanced
forloop to iterate over thefruitsarray. - In each iteration, prints the current fruit in uppercase using the
toUpperCase()method:someString.toUpperCase()
Cheat sheet
The enhanced for loop (for-each loop) provides a simpler way to iterate through arrays and collections without manual indexing:
for (data_type element : array_or_collection) {
// Code to be executed for each element
}data_type: The type of elements in the array or collectionelement: Variable that holds the current element in each iterationarray_or_collection: The array or collection to iterate over
Example with an integer array:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}The enhanced for loop is ideal when you need to access each element without modifying the collection itself.
Try it yourself
public class Main {
public static void main(String[] args) {
// Initialize the fruits array
// Use an enhanced for loop to iterate over the array
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else