0

I don't understand why this works and I hope somebody can explain it to me. Here is an example:

TestObject array[] = new TestObject[10];
for(int i= 0; i <= 10; i++){
    TestObject object = new TestObject();

     object.setValue(i);
     array[i] = object;
    System.out.println(array[i].getObject());
}

Why can I create multiple instances of "TestObject" with the same name in the loop? Usually you can't create instances with the same name:

TestObject o = new TestObject(1);
TestObject o = new TestObject(2);

Well, this will obviously throws an error...

Manan Shy
  • 23
  • 3
  • possible duplicate of [Declaring variables inside or outside of a loop](http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop) – Whymarrh Nov 01 '14 at 20:21

4 Answers4

3

The scope for a for loop is limited to the iteration. So TestObject object is created and destroyed in each iteration.

Khalid
  • 2,212
  • 11
  • 12
  • Thanks for answering! But I save every instance of TestObject in a global Array. Do they still have the same name in the array? – Manan Shy Nov 01 '14 at 20:27
  • You're not actually storing the objects' names. You're storing the objects' references. If you look inside the array, you'll see an array of unique objects with unique references. – Khalid Nov 01 '14 at 20:32
3

Every iteration of a loop is a block and, as a block, has its own scope. You can achieve the same result by doing this:

{
    int i = 0;
}
{
    int i = 1;
}
// etc
Tabaqui
  • 427
  • 1
  • 3
  • 11
0

This is because 'object' is in visibility scope of current loop iteration, so for next iteration, there can be initialized a new one with the same name (other scope).

Uhla
  • 368
  • 3
  • 11
0

it's the scope of object problem. every iteration has its scope let's say they are not the same object at all

Abbas Elmas
  • 422
  • 6
  • 16