Java for-each Loop

In Java, there is an alternative syntax of for loop to work with Java arrays and Java collections (known as for-each loop). For example,


\begin{lstlisting}
for (int a : array) {
System.out.println(a);
}
\end{lstlisting}

In Java, the for-each loop is used to iterate through each element of arrays or collections. It is also known as enhanced for loop. Here's what the for-each loop looks like in Java,


\begin{lstlisting}
for(data_type item : collections) {
...
}
\end{lstlisting}

Here,


\begin{lstlisting}
// The program below calculates the sum of all elements of an...
...m += number;
}
\par
System.out.println(''Sum = '' + sum);
}
}
\end{lstlisting}

The output looks like Sum = 19. We can also verity the difference between for loop and for-each loop with the help of below code blocks.



Subsections