# Java: Arrays -- Introduction

## Java arrays are similar to ideas in mathematics

An array can store many similar values in memory. The word "array" in Java means approximately the same thing as array, matrix, or vector does in math.

Unlike math, you must declare the array and allocate a fixed amount of memory for it.

## Declaring an array

An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable. The declaration only allocates space associated with a variable name for a reference to an array, but doesn't create the actual array object.

    String[] args;    // args is an array of Strings
    int[] scores;     // scores is an array of ints
    JButton[] bs;     // bs is an array of JButtons

Unlike some languages, never put the size of the array in the declaration because an array declaration only tells Java that the variable is an array and the element type.

## Allocating an array object

Create an array using `new`. This example creates an array of 100 int elements, from `a[0]` to `a[99]`.

    int[] a;           // Declares a to be an array of ints
    a = new int[100];  // Allocates an array of 100 ints

## Subscripts

Subscripts are enclosed in square brackets `[]`. `xi` in mathematics is `x[i]` in Java, and is pronounced "x-sub-i". The `[]` brackets are an operator in Java and have a precedence like other operators.

Subscript ranges always start at zero because Java came largely from C++, which had a good reason for using zero (pointer arithmetic on arrays). It isn't the way that humans normally count; you'll just have to live with it.

## Subscript checking

Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws `ArrayIndexOutOfBoundsException`. This is far superior to the behavior of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++.

## Length of an array

Each array has a constant (`final`) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by `.length`. In the previous example, `a.length` would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.

## Java idiom for looping over an array

The most common use of `.length` is in a for loop test condition. For example, the variable `i` will go over the entire range of subscripts of the array `a`.

    for (int i=0; i < a.length; i++) { . . .

## Example Version 1 -- Adding all elements of an array

These statements add the first n elements of an array. Assume that there are values in the array already.

    int[] a;           // Declare an array of ints
    a = new int[1000]; // Create an array of 1000 ints.
    ...
    int sum = 0;       // Start the total sum at 0.
    for (int i=0; i<a.length; i++) {
        sum = sum + a[i];  // Add the next element to the total
    }

## Example Version 2 -- Adding all elements of an array in Java 5

This is the the same as above, but uses the Java 5 "for each" loop, which frees you from using an index if you simply want to get all successive values.

    . . .
    for (int v : a) {
        sum = sum + v;  // Add the next element to the total
    }

## Initial array element values -- zero/null/false

When an array is allocated (with `new`), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float, ...), `false` for boolean, and `null` for all object types.

## Array variables are references to arrays

When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. When an array object is created with `new`, a reference is returned, and that reference can then be assigned to a variable. Similarly, you can assign one array variable to another, and it is only the reference that is copied. For example,

    int[] a = new int[] {100, 99, 98};
    int[] b;
    // "a" points to an array, and "b" doesn't point to anything
    b = a;      // now b points to the SAME array as "a"
    b[1] = 0;   // also changes a[1] because a and b are the same array.
    // Both a and b point to same array with value {100, 0, 98}

## Array Initialization

When you declare an array, you can can also allocate a preinitialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size. For example,

    // Java 1.0 style -- shorter, but can be used ONLY IN DECLARATIONS
    String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

The above way is the most common way to declare and initialize arrays.

## Library methods for arrays

Static methods for manipulating arrays are available in the `java.util.Arrays` class ( `asList()`, `binarySearch()`, `equals`, `fill()`, and `sort()`. In addition there is `System.arrayCopy()`.