Java for each loop | Enhanced for loop |
Posted: May 12, 2023 |
In this topic, we will learn about the for-each loop in java. A for-each loop was introduced in Java 1.5. This loop is also known as an enhanced for loop. This loop is used to traverse Collection or Array in java. It helps us avoid programming errors. It makes the code precise and readable. It's easier to implement. This loop avoids the chance of an infinite loop. Table of content1. Syntax of for-each loop 1. Syntax of for-each loopThe syntax of Java for-each loop is containing a data type with the variable name followed by a colon (:) symbol and then the data source is an array or collection. 2. How does the for-each loop work?The Java for-each loop is traversing the array or collection until the last element. The for each element, it stores the element in the variable and then executes the body of the for-each loop. 3. Example of traversing the array elementsOutput 4. Example of the sum of array elementsOutput 5. Example of traversing the collection elementsOutput 6. ConclusionIn this topic, we learnt about the for-each loop in java and its example
|
|||||||||||||||||||||||||||||||||||||||||||
|