Beginner Java: Simple array
Java Arrays are data structures containing objects of the same type. A String array can only contain Strings and a Car array can only contain car objects. Arrays are used to store objects that you want to use in other calculations or want to reference to. For example, an array can contain grades that can be averaged or referenced.
When you declare a Java array, you need to give it a data type when you declare it just like you would give a variable a datatype.
For example, we will declare an integer array containing five elements which we will name arrayName
int arrayName = new int;
When you need to access an element of the array you can do so directly :
or you can print out the entire array using a for loop - first put some values in it so we can see what is going on. Remember arrays start numbering with 0 so an array with a length of five has elements numbered from 0-4 and not 1-5.
arrayName = 000;
arrayName = 111;
arrayName = 222;
arrayName = 333;
arrayName = 444;
To print out the entire array (five is the size of the array):
for (int i=0; i<5; i++)
} // end for
This will print out the following:
When you declare arrays, they are a fixed length and cannot be any other size. If you need to increase the size of an array, you can declare a new array that is a larger size and copy the first array into it using a loop. You then re-declare an array using the first array name making it the same size (or larger) than the second array and copying it back into the new array (that has the same name as the original array) You can place this code into a method and call it whenever we need to increase the array size. This is a work around for using an array that needs to grow. The best solution is to use an ArrayList which can grow as needed although that is beyond the scope of this beginner Java article.