Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does primitive array work with new for each loop in Java?

Tags:

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) {  } 
like image 300
AS_ Avatar asked Jan 10 '13 19:01

AS_


People also ask

How is forEach loop used in Java with arrays?

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.

Can you create an array in a for loop Java?

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.

How do you initialize a primitive array in Java?

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.

Are for each loops only for arrays?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

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.

like image 141
Patricia Shanahan Avatar answered Sep 28 '22 19:09

Patricia Shanahan