Java: Arrays
Arrays are another way to store data.
To start explaining arrays I'm going to use an example..
Lets say you own a sweet factory, and you have robots making lollipops. You've decided that you want to make a java program that tracks how many lollipops each robot has made.
Well before this lesson you would have had to create a variable for each robots progress, however this is where arrays can save you lots of time and are very helpful.
We just create a single array and we can store all our data in, so lets start creating the array.
To start you have to specify the data type, all of the data in the array must use the same datatype; immediately after the datatype we open and close square brackets, this is how the compiler knows its an array.
If you wanted to initialise the variables later after declaration then you could just stop here for now, and asign the values manually.
However its much easier just to add an equals sign (like assigning a normal variable) then open curly brackets, inside the curly brackets input the values (separated by commas).
An example of this would be:
int[] ArrayOne = {3, 12, 42, 59};
In this example the array has four pieces. However when referring to them we start counting from zero, so 0 is 3, 1 is 12, 2 is 42, and three is 59.
We refer to pieces of the array like so:
ARRAYNAME[REFERALNUMBER]
So going back to our example if we wanted to refer to 59 we would use:
ArrayOne[3]
Here is a simple application that uses a for loop to output different array values:
int[] ArrayOne = {3, 12, 42, 59};
int x = 0;
for(int y = 4; x < y; x++){
System.out.println(ArrayOne[x]);
}
Back to Java

