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

What are enhanced for loops in Java? | ComputerScienceOne | Bifalgorithm | Bifalgorithm