+ 2
Can somebody help me Understand Arrays in Java better?
I don't understand anything about arrays in Java because this array lesson was not simply and it is really confusing. And for that reason I can't continue with the leaning. I'm stacked here. can somebody simplify this java Array lesson for me ?
1 Answer
+ 8
Okay, an array is a BUNCH of variables.
However, all variables in the array are of the type of the array.
For example,
int[] array1 = {5,2,3,6};
Notice that everything in the array is an int. This is because I said "int[]" meaning, an array of type int.
So, the following would cause an error:
int[] array2 = {"A string!", 5, 3};
Now, moving on to some terminology:
Each ITEM in the array is called an element.
Each element contains some data (Or, the elements value). This is what's in the array.
For example,
int[] array3 = {1,2,3};
// 1 2 and 3 are the elements
Now, this is important:
The location of each element is called the Index.
(Originally defined as: The distance from the starting point in the array).
To access or modify an element, you can use this index.
ALL ARRAYS BEGIN AT THE INDEX 0.
Example/
int[] array4 = {5,7,9,0};
The index's are like this:
value: 5 7 9 0
index: 0 1 2 3
System.out.println(array4[2])
// Output: 9
So, we use the syntax:
myArrayName[index] to get or modify the element at that index in the array.