Arrays
Submitted by GeePee on Tuesday, June 9, 2015 - 22:31.
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}]:
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...
Next lets output the values of each placement in our array...
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...
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.
- int[] myArray = new int[10];
- myArray[0] = 0;
- myArray[1] = 10;
- myArray[2] = 100;
- myArray[3] = 1000;
- myArray[4] = 10000;
- for (int i=0;i<myArray.length;i++){
- }
- myArray[0] = 100000;
- for (int i=0;i<myArray.length;i++){
- }
0
10
100
1000
10000
0
0
0
0
0
100000
10
100
1000
10000
0
0
0
0
0
Finished!Add new comment
- 191 views