Arrays





Recall what we said about reference types:




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






Declaring and Creating Arrays



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


Type[] arrayName;



Example:
char[] charsInMyName; 

Note: Sets aside 4 bytes to store the memory location of an array of type char. This variable, charsInMyName, does NOT point to an actual array - it is un-initialized.


Example: Declare a reference variable to an array of integers
int[]  intArray;

Note: intArray will contain the address of an array of integers. This declaration does not allocate memory for the array - it sets aside 4 bytes to store the address of an array.





2. Setting aside memory for the array elements:


arrayName = new Type[numElts];

This statement sets aside memory for the array of elements, and stores address of array in arrayName.
                                                        


Example:
charsInMyName = new char[4];
intArray = new int[120];



3. The above two steps are often combined:

char[] charsInMyName = new char[4];
int[]  intArray = new int[120];



4. We can also declare and initialize an array at the same time:

char[] charsInMyName = {'M', 'a', 'r', 'y'};










Examples


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




Example: If we want to store and use 100 Strings that represent 100 employee's passwords in our program, it is not practical to use a different variable name to refer to each String. Instead, we store the records in an array of String objects.

Instead of:
   String mike;
  String sam;
  String julie;
...


We use an array that contains 100 String objects:
String[] employeeInfo = new String[100];


In this Java statement, we have:







Indexing Arrays



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



Example:
char[] charsInMyName = {'M', 'a', 'r', 'y'};
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.

System.out.println(nums[0]);


Exercise: Write a Java statement that prints the last 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++)
   System.out.println(vals[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
arrayName.length



Example: Printing an array's entries

int[ ] primes = new primes[5];
for(int i = 0; i < primes.length; i++)
       System.out.println(primes[i]);





Common Errors


1. Forgetting to Initialize an Array

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

Example:
double[ ] data;
data[0] = 15.5; 

Note: Error - no memory has been allocated for the array elements yet.

Instead:
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!

Example:
double[ ] data = new double[20];
data[20] = 15.5;

Note: Error - the valid index values are 0, 1, ..., 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



Example:
int[ ] primes = {2, 3, 5, 7, 11, 13};
int[ ] numbers = primes; 
numbers[5] = 12;


The reference variables numbers and primes point to the same array.
Now primes[5] is also 12.  So:



Note: To actually copy all the elements of one array to a different array, you could use a loop.

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.





Another way: You can also copy all values from one array to another using the arraycopy() method in the System class.

Note:
This is a static method.

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


Example:

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++)
          System.out.println(numbers[i]);
    }
}



Output:
2
3
21
22
23
24




Exercise: Write a program that reads 10 integers from the user, and then prints the average, minimum, and maximum for those integers.



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.


Exercise: Write a method called lastIndex that takes an array of integers and an integer as its arguments, and returns the last index at which the integer value occurs in the array. The method should return -1 if the integer value is not found in the array.