1

I am learning java, I just want to make sure I am understand this line of code properly. It is as follows:

public class DataStructure {

private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];

public DataStructure() {
    for (int i = 0; i < SIZE; i++) {
        arrayOfInts[i] = i;
    }
}

The line I am not sure about is:

arrayOfInts[i] = i;

Is this saying that in the array, index 0 will produce an int value of 0, and index 2 will produce an int value of 2, and so on...?

3
  • It's not "producing" a value. You're assigning the value i to that position in the array. After the loop, your array will be {0,1,2,3,4,...,13,14}.
    – pushkin
    Commented Dec 11, 2015 at 2:55
  • Yes. You are essentially adding a value(equal to index) in array for a particular index
    – achin
    Commented Dec 11, 2015 at 2:55
  • Did my answer help? If so, please press the check mark under the like button to indicate so. If you need any more help, feel free to ask! Commented Dec 11, 2015 at 5:47

3 Answers 3

4

Just to be clear, because I know this can be confusing, i is an int. By doing:

arrayOfInts[i] = i;

You are finding the i index. Where i is an int. So, if i is 7, it will be the 6th number of the array. Why not the 7th? Because it starts at 0:

enter image description here (From the java docs)

So, lets say i is 7, right? It will be the 6th number. THAT IS IMPORTANT, and hopefully saves you lots of time with arrays.

0

Yes, you are correct. arrayOfInts[i] = i; means that at index i of the array arrayOfInts, the value is set to the integer i. So at index 0, it will have a value of 0; index 1 will have a value of 1 and so on. I hope this helps!

0

Rather than "produing" a value, as you stated, you are assigning a value to that index in the Array. If you were to go through the loop iteratively and wrote down each statement's outcome it would look like this if we use the logical statement arrayOfInts[i] = i

// first iteration
arrayOfInts[0] = 0;
i = i + 1;

// second iteration
arrayOfInts[1] = 1;
i = i + 1;

// third iteration
arrayOfInts[2] = 2;
i = i + 1;

So on and so forth. At the end of the iteration you will have a completely assigned Array that ends in the result

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

Also always keep in mind as you learn more programming techniques and languages that in computer science we start counting at 0 instead of 1. It took me quite a while to get that through my head.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.