Java Lecture 8: Arrays

In ML, we had lists of values. In Java, we have arrays of variables

  1. Already seen the array of command-line arguments: String Args[]
  2. 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
  3. Each index value denotes a different variable; it can be used or stored to separately from all other indices in the array
    1. E.g., A[0] is a variable, A[1] is a variable, A[2] is a variable, etc...
    2. We call each of these an element in A
  4. Of course, we usually use an array to hold values that are related somehow
  5. 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
  6. Declaring an array is done by adding (empty) square brackets onto the array name or the type name (but not both!)
    1. E.g., "int A[];" and "int[] A;" both declare an array A of integers, but "int[] A[];" does not.
  7. The declaration does not create the array, only that the name A will be an array
  8. To create the array, we need to do a "new" assignment statement, like "A = new int[25];"
    1. That make A to be an array of 25 integer variables.
  9. The declaration and creation can be combined like "int A[] = new int[25];"
  10. An integer array that is created using "new" has initial values of 0 for all of its elements.
  11. Another way of creating an array at declaration time is to use an initializer list.
    1. E.g, like "int A[] = {4,3,2,5,6};"
    2. 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, ...)
  12. Example program with arrays.