Java Lecture 8: Arrays
In ML, we had lists of values. In Java, we have arrays of variables
- Already seen the array of command-line arguments: String
Args[]
- Arrays are indexed by an integer value (could be from a variable
or expression) that is between 0 and 1 less than the size of the array
- Each index value denotes a different variable; it can be used or stored
to separately from all other indices in the array
- E.g., A[0] is a variable, A[1] is a variable, A[2] is a variable, etc...
- We call each of these an element in A
- Of course, we usually use an array to hold values that are related
somehow
- The addition of a ".length" onto the array
name is an identifier for the size of the array. It is one bigger than
the maximum index into the array
- Declaring an array is done by adding (empty) square brackets onto the
array name or the type name (but not both!)
- E.g., "int A[];" and "int[] A;"
both declare an array A of integers, but "int[] A[];"
does not.
- The declaration does not create the array, only that the name A will
be an array
- To create the array, we need to do a "new"
assignment statement, like "A = new int[25];"
- That make A to be an array of 25 integer variables.
- The declaration and creation can be combined like "int
A[] = new int[25];"
- An integer array that is created using "new"
has initial values of 0 for all of its elements.
- Another way of creating an array at declaration time is to use an initializer
list.
- E.g, like "int A[] = {4,3,2,5,6};"
- This creates an array for A that is of size 5, and whose elements are
intialized to the values given, in order (i.e., A[0]==4, A[1]==3, ...)
- Example program with arrays.