|
Understanding the Use of Arrays
with Examples in Java |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
What do you think of the following fragment?
Arrays offer the same kinds of benefits of subscripts in mathematical notation -- this fragment is more compact, more readable, and more flexible.
[]
Modifier:
int[] income;
[]
Length Specifier:
income = new int[20];
[]
Operator:
income[5] = 250000;
x = payment(income[0]);
payment(int[] income)
main(String[] args)
y = meanPayment(taxableIncome);
public int[] schedule(){...}
length contains the number of elements (and
is initialized when memory is allocated)clone() makes a (shallow) copylength Attribute
length Attribute (cont.)
clone() Method
length
NullPointerException when using method/attribute
IndexOutOfBoundsException when accessing
an elementArrays Utility Class
The Arrays class (in the java.util package)
class contains several static methods that are very convenient when
working with arrays.