SmRndGuy
SmRndGuy

Reputation: 1819

Why aren't array elements initialized in an enhanced for loop?

When I use normal for-loop,
all elements in an array will initialize normally:

Object[] objs = new Object[10];
for (int i=0;i<objs.length;i++)
        objs[i] = new Object();


But when I use a for-each loop.
the array elements are still null, after the loop:

Object[] objs = new Object[10];
for (Object obj : objs)
        obj = new Object();


I thought obj refers to a particular element in an array,
so if I initialize it, the array element will be initialized as well.
Why isn't that happening?

Upvotes: 5

Views: 1097

Answers (4)

Kanchan
Kanchan

Reputation: 840

You are assigning new object to array element (Which is a variable that would be a reference to an Object) which can be accessed outside the for loop.

Object[] objs = new Object[10];
for (int i=0;i<objs.length;i++)
objs[i] = new Object();

But in for each loop you are assigning the new object to the local variable (not array elements)

Object[] objs = new Object[10];
for (Object obj : objs){
obj = new Object(); 
}
//obj can not be accessed here

and If we talk about this line

     for (Object obj : objs){

Then its means is that you are taking the value of objs element to the local variable obj, which is null.

Upvotes: 0

sandymatt
sandymatt

Reputation: 5612

Object[] objs = new Object[10];
for (Object obj : objs)
  obj = new Object();

You've created the space where the objects will go, but you haven't actually created the objects. This will try to iterate over the objects in the array if they exist (which they don't yet!)

Object[] objs = new Object[10];
for (int i=0; i < objs.length; i++)
  objs[i] = new Object();

This is different due to the fact that you're just simply counting from 0 to 9, and creating + storing them in the appropriate spot in the array.

Upvotes: 1

Jhanvi
Jhanvi

Reputation: 5139

You are assigning the new value to 'obj' and not to the 'objs' , hence the elements are null. You have to assign the value to objs also:

    Object[] objs = new Object[10];
    for (int k = 0; k < objs.length; k++) {
        objs[k] = new Object();
        System.out.println(objs[k]);
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500865

I thought obj refers to a particular element in an array, so if I initialize it, the array element will be initialized as well. Why isn't that happening?

No, obj has the value of the array element at the start of the body of the loop. It isn't an alias for the array element variable. So a loop like this (for arrays; it's different for iterables):

for (Object obj : objs) {
    // Code using obj here
}

Is equivalent to:

for (int i = 0; i < objs.length; i++) {
    Object obj = objs[i];
    // Code using obj here
}

See section 14.14.2 of the JLS for more details of the exact behaviour of the enhanced for loop.

Upvotes: 9

Related Questions