I'm really new to Java and am just struggling with arrays a little bit. I've got a block of code that I've written when following a tutorial but am struggling to understand it and would love if someone could explain it to me.
I've tried working through it with various different methods (explaining to my duck, writing it down, etc.) and still can't get my head around it. I normally wouldn't ask and I always try desperately hard to work it out myself, but I just can't figure it out this time.
int[] values = new int[3];
values[0] = 10;
values[1] = 20;
values[3] = 30;
for(int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
I understand why:
- The for loop iterates through the values in "values".
- The loop keeps looping until i is less than the last value in the array.
But what I don't understand is why I need to write values[i] in the System.out.println() statement. What tells Java that i can be used in the array values[]?
Sorry if this is a trivial question for you but this is the best place I could think of to turn.
[index]accesses the element of the array at theindex.ArrayOutOfBoundsExceptionon rowvalues[3] = 30;, since3points to 4th array element.values [2]instead ofvalues[3], because Java arrays are 0-indexed and so an index of 3 indicates the 4th array elegant, which dies not exist asvalueswas assigned to be a 3-element array, and otherwise you would get an ArrayIndexOutOfBoundsException.