Concept
What are enhanced for loops in Java?
ComputerScienceOne / Enhanced For Loops
"Java also supports foreach loops (which were introduced in JDK 1.5.0) which Java refers to as “Enhanced For Loops.” Foreach loops allow you to iterate over each element in a collection without having to define an index variable or otherwise “get” each element. We’ll revisit these concepts in detail in Chapter 31, but let’s take a look at a couple of examples. An enhanced for loop in Java still uses the keyword for but uses different syntax for its control. The example in Code Sample 28.5 illustrates this syntax: (int a : arr) . The last element of this syntax is a reference to the collection that we want to iterate over. The first part is the type and local reference variable that the loop will use.\n\n1 int arr[] = {10, 20, 8, 42};\n\n2 int sum = 0;\n\n3 for(int a : arr) {\n\n4 sum += a;\n\n5 }\n\nCode Sample 28.5.: Enhanced For Loops in Java Example 1"
Related Ideas
- How can you iterate over Java arrays?ComputerScienceOne · Basic Usage
- How does an enhanced for loop calculate the sum of integers in a Java list?ComputerScienceOne · Normalizing a Number
- How does an enhanced for loop compute the sum of a list of integers?ComputerScienceOne · Summation
- How are for loops structured and scoped in Java?ComputerScienceOne · Do-While Loops
- How is a basic while loop structured in Java?ComputerScienceOne · While Loops
- How do nested loops execute in Java?ComputerScienceOne · Nested Loops
- How do do-while loops differ from while loops in Java?ComputerScienceOne · For Loops
- How does PHP use foreach loops to iterate over array elements?ComputerScienceOne · Foreach Loops