I understand that new for each loop works with Iterable and arrays, but I don't know what goes behind the scenes when working with arrays.
Can anyone help me understand this? Thanks in advance.
int[] number = new int[10]; for(int i: number) { }
The Java for-each loop traverses the array or collection until the last element. For each element, it stores the element in the variable and executes the body of the for-each loop.
Java Arrays LoopYou can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
The loop is equivalent to:
for(int j = 0; j < number.length; j++) { int i = number[j]; ... }
where j is an internally generated reference that does not conflict with normal user identifiers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With