JohnG JohnG - 3 months ago 7
Java Question

How does this for-loop know how long this array datastructure will be from the start?

I am trying to figure out how the array knows that there are a total of 15 indexes from the first run of System.out.println in the for-loop, and from where EXACTLY it knows it.

It seems to know the total number of indexes while the for-loop is still executing, and I thought that once an array is created, that it cannot be changed. Is the array in a temporary state while it's being constructed, or is the answer much simpler than I'm making it?

I'm making guesses at the possible answer, and I do not know for sure. Please help! Thank you in advance.

My sole purpose in using this code is to evaluate the resulting output at the bottom compared to the code used to create it, and determine how this particular for-loop constructs the array.

import java.util.Arrays;

public class DataStructureMain {

public static void main(String[] args) {

class DataStructure {

//Create an array
private final static int SIZE = 15;
private int[] anArrayOfInts = new int[SIZE];

public DataStructure() {

//Fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
anArrayOfInts[i] = i;
//I put this next line in here to see how the code
//executes each run of the for-loop
System.out.println(Arrays.toString(anArrayOfInts));
}
}
}

//
//
DataStructure dS = new DataStructure();

}

}


Produces this:



[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]


Answer

You set
SIZE = 15;
then you use the same variable to construct the array by
private int[] anArrayOfInts = new int[SIZE];.
Once it is created its size is fixed.
Then you use the same variable to limit the number of iterations by
for (int i = 0; i < SIZE; i++)

Alternatively you could use :
for (int i = 0; i < anArrayOfInts.length ; i++)
which would give you the same result.