Recall what we said about reference types:

An array is a collection of data items of the same type.


We can declare an array to hold 50 exam grades:
int[] examScores = new int[50];

Example: If we want to store and use 100 employee records in our program, it is not practical to use a different variable name to refer to each employee record. Instead, we store the records in an array of Employee objects.

Instead of:
Employee mike;
Employee sam;
Employee julie;

We use an array that contains 100 employee objects:
Employee[] empRecords = new Employee[100];

In this Java statement, we have:

One-Dimensional Arrays

Declaring an Array and Allocating Memory for It

1. Declaring an array without setting aside memory for the elements:

Type[] arrayName;

char[] charsInMyName;  // sets aside 4 bytes to store the memory location of an array
                                         // of chars
                                          // this variable, charsInMyName, doesn't point to an actual
                                             // array; it is un-initialized

2. Setting aside memory for the array elements:

arrayName = new Type[numElts]; // sets aside memory for the array elements, and
                                                     // stores address of array in arrayName

charsInMyName = new char[4];

3. These 2 steps are often combined:

char[] charsInMyName = new char[4];

4. We can also declare and initialize an array at the same time:
char[] charsInMyName = {'M', 'a', 'r', 'y'};

Indexing Arrays

Given an array arr of n elements, the elements of arr are named
arr[0], arr[1], arr[2], ... arr[n-1].

charsInMyName[0] is 'M'
charsInMyName[3] is 'y'

The only valid array indices, or subscripts, for the charsInMyName array, are 0, 1, 2, and 3. If I try to use a negative index or an index greater than 3, this will result in a run-time error. These out-of-bounds array subscripts would lead to an IndexOutOfBoundsException.

Recall: Exceptions are Java's way of handling run-time errors.

More on Initializing Arrays

We can initialize an array when we declare it. But we can also initialize the array elements after declaration as well:

int[] nums = new int[5];
nums[0] = 2;
nums[1] = 3;
nums[2] = 5;
nums[3] = 7;
nums[4] = 11;

Example: Write a Java statement that prints the first element in the array nums.


Example: Given the following array:
double[] vals = new double[100];
... // vals is initialized
Write Java code that prints each entry in vals on a separate line.

for(int i = 0; i < 100; i++)

Exercise: Create an array of 50 integers that contains the squares of the integers 1, 2, 3, ... 50. Then print the array.

Default Initial Values for Array Elements

When an array is first created, the elements are initialized to:

Array Length

To find the number of elements in an array, use

Ex: Printing an array's entries
int[ ] primes = new primes[5];
for(int i = 0; i < primes.length; i++)

Common Errors

1. Forgetting to Initialize an Array

Often a programmer will allocate an array reference, but forget to allocate the actual array.

double[ ] data;
data[0] = 15.5;  // error - no memory has been allocated for the array elements yet

double[ ] data = new double[20];
data[0] = 15.5;

2. Out of Bounds Array Access

Don't try to access non-existent positions in an array!

double[ ] data = new double[20];
data[20] = 15.5; // error - the valid index values in array data are 0, 1, 2, ... 19.

3. Determining Length Incorrectly

Java syntax for determining the length of an array and the length of a string is inconsistent.

Data Type            Number of Elements
Array                        a.length
String                        a.length()

Copying Arrays

int[ ] primes = {2, 3, 5, 7, 11, 13};
int[ ] numbers = primes;  // Now the reference variables numbers and primes point
                                         // to the same array
numbers[5] = 12;

Now primes[5] is also 12.  One array, 2 variables that hold its' address.

Exercise: Define 2 arrays of type int with 10 elements each, and read values from the keyboard to intialize the first one. Then copy all the entries in the first array to the second.

Note: This is a static method.

System.arraycopy(from, fromIndex, to, toIndex, count);


public class ArrayEx
    public static void main(String[] args)
       int[ ] primes = {2, 3, 5, 7, 11, 13};
       int[ ] numbers = {19, 20, 21, 22, 23, 24};

       System.arraycopy(primes, 0, numbers, 0, 2);
       // print numbers
       for(int i = 0; i < numbers.length; i++)


Exercise: Recall the Circle class we wrote previously. Write a program that creates an array containing 10 circles, and reads the radius value for each circle from the keyboard. For each circle, print the radius, area, and circumference.

Exercise: Use a loop to read ten strings and insert them into an array. Write another loop that prints out the strings in the opposite order from which they were entered.

Some Examples

Remember our Dog class?
1. Declare a Dog array variable:

    Dog[] pets;

2. Create a new Dog array with length 5, and assign it to the variable pets

    pets = new Dog[5];

Question: So what does variable pets hold?

3. Create new Dog objects, and assign them to the array elements:

    pets[0] = new Dog("Milo", 15);  // pets[0] holds a pointer to our new Dog object
    pets[1] = new Dog("Otis", 25);

Question: What is the current value of pets[2]?

Question: What code makes pets[3] refer to one of our existing Dog objects?

Example: Make the first Dog in our pets array bark:



Practice with Arrays

Prompt the user to enter integers in the range [0, 50] and count how many occurrences of each are entered. After all input has been processed, print all the values in [0, 50] that were entered at least once (with the number of occurrences). The first value entered by the user should be the number of  integers that will be entered.

Exercise: Write a program that reads a sentence from the user and counts the number of each uppercase and each lowercase letter in it.

Exercise: Write Java code that creates an array that contains the first 100 even positive integers. Then create a second array of 100 integers, and use a single Java statement to copy the contents of the first array into the second array.

Arrays as Arguments

public class changeArray
    public static void oops(int[] a)
       int n = a.length; // notice that this is not a method call!
       int zero = a[0];
       a[0] = a[n-1];
       a[n-1] = zero;
    } // what does this method do??

    public static void main(String[] args)
       int[] myArray = {1, 2, 3, 4};
       for(int i = 0; i < myArray.length; i++)


Exercise: Write a program that reads 10 integers from the keyboard and stores them in an array. Write a method called reverse that reverses the order of the elements in the array. In the main method, print the array, call reverse, and then print the array again.

Exercise: Write a program that contains a method that takes an array of doubles and returns the sum of the array's elements.

Arrays as Return Values


public class genArray
    public static int[ ] fillArray(int size)
          // Creates array containing integers 1 to size
          int[ ] result = new int[size];

          for(int i = 0; i < size; i++)
             result[i] = i+1;
          return result;

    public static void main(String[] args)
       int[ ] a = fillArray(5);
       for(int i = 0; i < a.length; i++)


Exercise: Write a program that includes a method that takes 2 integers and creates and returns an array that contains all the integer values between them. That is, if the integers passed to the method are -1 and 7, the method should return an array that contains -1, 0, 1, 2, 3, 4, 5, 6, 7. In your main method, call this method to create several arrays and then print them.

Exercise: Write a method numberLessThan() that takes an int array a and an int valuev, and returns the number of elements in a that are less than v.