Java Arrays Introduction
Suppose we have a requirement to store average mark scored by each student. To accomplish this we define different variables (identifiers) of type double to store each student’s average mark.
double student1Avg; double student2Avg; double student3Avg; … … … student1Avg = 60.5; student2Avg = 85.5; student3Avg = 94.5; …
As you can see, it seems like a tedious task in order to create many different variables, initialize and use them especially if they are used for the same purpose.
To solve this problem, we have arrays.
What is an Array?
- An array is a container object that holds a fixed number of elements of a single type.
- Arrays are always objects whether it is declared to hold primitive or object.
- The length of an array is established when the array is created. After creation, its length is fixed.
Following are the steps involved in using an array.
- Declare an array
- Construct an array i.e.) allocating memory on the heap
- Initialize an array with elements
- Access array elements.