Introduction:
Welcome, this page will teach you about Arrays within Java.
What is an Array?
An array is a variable which holds more than one value, in effect, it's a list of values attached to a variable name.
When are Arrays Used?
Arrays are very useful for holding lists of values for certain scripts. For example; holding the id of each button that has been activated within a game. Once a button is clicked, it's ID gets added to the array of clicked buttons which then gives a list of clicked button ids to be used at a later date.
Examples:
First we need to decide what type of variable the array will hold, the amount of data it will hold (maximum) and we also need a variable name. Once we have those we can create our new array using the format {type}[] {variable name} = new {type}[{size}]:
int[] myArray = new int[10];
The above code will create a new variable named "myArray" which is equal to a new int array of 10 values (technically it is 9 values, and 0). Now we are able to insert values in to the 10 spaces within our new array, such as...
myArray[0] = 0;
myArray[1] = 10;
myArray[2] = 100;
myArray[3] = 1000;
myArray[4] = 10000;
Next lets output the values of each placement in our array...
for (int i=0;i<myArray.length;i++){
System.
out.
println(myArray
[i
]); }
You are also able to edit previously set values. Lets change the first value (0) to 100000 then re-output all the values to our console and observe the change...
myArray[0] = 100000;
for (int i=0;i<myArray.length;i++){
System.
out.
println(myArray
[i
]); }
Here is the output to the console we get in total once we run the program. As you can see;
1 - There is a change in value 0, as we attempted.
2 - There are alot of "0"s after the ending 4 (5) value of our integer array which we had set. This is because, even if the placements don't have a custom, user set value, they still exist and have a default value.
0
10
100
1000
10000
0
0
0
0
0
100000
10
100
1000
10000
0
0
0
0
0
Finished!