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...

1

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answering! But I save every instance of TestObject in a global Array. Do they still have the same name in the array?
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.
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

Comments

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).

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.