Java Reference
In-Depth Information
Note It is possible to create an array of Objects ( Object[] ) that can hold refer-
ences to objects of different types; however, this is not recommended as it requires you
to check the type of elements and perform explicit type casting when retrieving ele-
ments from the array.
There are two steps to completely defining an array object in Java: array variable
declaration, which specifies the array element type, and array creation, which allocates
the memory for the array. Once an array is declared and the memory is allocated, it can
be initialized. There are multiple ways to initialize an array, which are shown in the
solution to this recipe. If you know in advance what data you need to store in the array,
you can combine array declaration, creation, and initialization in one step using a short-
cut syntax you will see demonstrated in the solution.
Let's walk through the GradeAnalyzer class and examine the various ways to
declare, create, initialize, and access arrays. First, notice that the class has one instance
variable to hold the grades to be analyzed:
private int[] _grades;
Like all other uninitialized Object reference instance variables, the _grades ar-
ray instance variable is automatically initialized to null . Before you can start analyz-
ing grades, you have to set the _grades instance variable to reference the grades data
you want to analyze. This is done using the setGrades(int[]) method. Once
GradeAnalyzer has a collection of grades to analyze, the meanGrade() ,
minGrade() , and maxGrade() methods can be called to compute their respective
statistics. Together, these three methods demonstrate how to iterate over the elements
of an array, how to access elements of an array, and how to determine the number of
elements an array can hold. To determine the number of elements an array can hold,
simply access the implicitly defined, final instance variable, length , which is defined
for all arrays:
_grades.length
To iterate over the elements of an array, simply use a for loop, whose index vari-
able goes through all possible indices of the array. Array indices start at 0 , so the last
array index is always ( _grades.length - 1 ). While iterating over the array, you
can access the array element at the current index by using the name of the array vari-
Search WWH ::




Custom Search