An array is a data structure that stores a collection of values of the same type. You access each individual value through an integer index. For example, if a is an array of integers, then a[i] is the ith integer in the array. You declare an array variable by specifying the array type-which is the element type followed by []-and the array variable name. For example, here is the declaration of an array a of integers:

int[] a;

However, this statement only declares the variable a. It does not yet initialize a with an actual array. You use the new operator to create the array.

int[] a = new int[100];

This statement sets up an array that can hold 100 integers. The array entries are numbered from 0 to 99 (and not 1 to 100). Once the array is created, you can fill the entries in an array, for example, by using a loop:

int[] a = new int[100];
for (int i = 0; i < 100; i++)
 a[i] = i; // fills the array with 0 to 99

Java graphics caution_icon

If you construct an array with 100 elements and then try to access the element a[100] (or any other index outside the range 0 . . . 99), then your program will terminate with an "array index out of bounds" exception.To find the number of elements of an array, use arrayName.length. For example,

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

Once you create an array, you cannot change its size (although you can, of course, change an individual array element). If you frequently need to expand the size of an array while a program is running, you should use a different data structure called an array list. (See for more on array lists.)Java graphics notes_icon

You can define an array variable either as

int[] a;

or as

int a[];

Most Java programmers prefer the former style because it neatly separates the type int[] (integer array) from the variable name.

Array Initializers and Anonymous Arrays

Java has a shorthand to create an array object and supply initial values at the same time. Here's an example of the syntax at work:

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };

Notice that you do not use a call to new when you use this syntax. You can even initialize an anonymous array:

new int[] { 17, 19, 23, 29, 31, 37 }

This expression allocates a new array and fills it with the values inside the braces. It counts the number of initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable. For example,

smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };

is a shorthand for

int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;

Java graphics notes_icon

It is legal to have arrays of length 0. Such an array can be useful if you write a method that computes an array result, and the result happens to be empty. You construct an array of length 0 as

new elementType[0]

Note that an array of length 0 is not the same as null. (See for more information about null.)

Copying Arrays

You can copy one array variable into another, but then both variables refer to the same array:

int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12; // now smallPrimes[5] is also 12

shows the result. If you actually want to copy all values of one array into another, you have to use the arraycopy method in the System class. The syntax for this call is

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

Copying an array variable

Java graphics 03fig14

The to array must have sufficient space to hold the copied elements. For example, the following statements, whose result is illustrated in , set up two arrays and then copy the last four entries of the first array to the second array. The copy starts at position 2 in the source array and copies 4 entries, starting at position 3 of the target.

int[] smallPrimes = {2, 3, 5, 7, 11, 13};
int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};
System.arraycopy(smallPrimes, 2, luckyNumbers, 3, 4);
for (int i = 0; i < luckyNumbers.length; i++)
 System.out.println(i + ": " + luckyNumbers[i]);

Copying values between arrays

Java graphics 03fig15

The output is:

0: 1001
1: 1002
2: 1003
3: 5
4: 7
5: 11
6: 13

Java graphics cplus_icon

A Java array is quite different from a C++ array on the stack. It is, however, essentially the same as a pointer to an array allocated on the heap. That is,

int[] a = new int[100]; // Java

is not the same as

int a[100]; // C++

but rather

int* a = new int[100]; // C++

In Java, the [] operator is predefined to perform bounds checking. Furthermore, there is no pointer arithmetic-you can't increment a to point to the next element in the array.

Command Line Parameters

You have already seen one example of Java arrays repeated quite a few times. Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings, namely, the arguments specified on the command line. For example, consider this program:

public class Message
{
 public static void main(String[] args)
 {
 if (args[0].equals("-h"))
 System.out.print("Hello,");
 else if (args[0].equals("-g"))
 System.out.print("Goodbye,");
 // print the other command line arguments
 for (int i = 1; i < args.length; i++)
 System.out.print(" " + args[i]);
 System.out.println("!");
 }
}

If the program is called as

java Message -g cruel world

then the args array has the following contents:

args[0]: "-g"
args[1]: "cruel"
args[2]: "world"

The program prints the message

Goodbye, cruel world!

Java graphics cplus_icon

In the main method of a Java program, the name of the program is not stored in the args array. For example, when you start up a program as

java Message -h world

from the command line, then args[0] will be "-h" and not "Message" or "java".

Sorting an Array

If you want to sort an array of numbers, you can use one of the sort methods in the Arrays class:

int[] a = new int[10000];
. . .
Arrays.sort(a)

This method uses a tuned version of the QuickSort algorithm that is claimed to be very efficient on most data sets. The Arrays class provides several other convenience methods for arrays that are included in the API notes at the end of this section. The program in puts arrays to work. This program draws a random combination of numbers for a lottery game. For example, if you play a "choose 6 numbers from 49" lottery, then the program might print:

Bet the following combination. It'll make you rich!
 4
 7
 8
 19
 30
 44

To select such a random set of numbers, we first fill an array numbers with the values 1, 2, . . ., n:

int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
 numbers[i] = i + 1;

A second array holds the numbers to be drawn:

int[] result = new int[k];

Now we draw k numbers. The Math.random method returns a random floating point number that is between 0 (inclusive) and 1 (exclusive). By multiplying the result with n, we obtain a random number between 0 and n - 1.

int r = (int)(Math.random() * n);

We set the ith result to be the number at that index. Initially, that is just r itself, but as you'll see presently, the contents of the numbers array is changed after each draw.

result[i] = numbers[r];

Now we must be sure never to draw that number again-all lottery numbers must be distinct. Therefore, we overwrite numbers[r] with the last number in the array and reduce n by 1.

numbers[r] = numbers[n - 1];
n--;

The point is that in each draw we pick an index, not the actual value. The index points into an array that contains the values that have not yet been drawn. After drawing k lottery numbers, we sort the result array for a more pleasing output:

Arrays.sort(result);
for (int i = 0; i < result.length; i++)
 System.out.println(result[i]);

Example LotteryDrawing.java

 1. import java.util.*;
 2. import javax.swing.*;
 3.
 4. public class LotteryDrawing
 5. {
 6. public static void main(String[] args)
 7. {
 8. String input = JOptionPane.showInputDialog
 9. ("How many numbers do you need to draw?");
10. int k = Integer.parseInt(input);
11.
12. input = JOptionPane.showInputDialog
13. ("What is the highest number you can draw?");
14. int n = Integer.parseInt(input);
15.
16. // fill an array with numbers 1 2 3 . . . n
17. int[] numbers = new int[n];
18. for (int i = 0; i < numbers.length; i++)
19. numbers[i] = i + 1;
20.
21. // draw k numbers and put them into a second array
22.
23. int[] result = new int[k];
24. for (int i = 0; i < result.length; i++)
25. {
26. // make a random index between 0 and n - 1
27. int r = (int)(Math.random() * n);
28.
29. // pick the element at the random location
30. result[i] = numbers[r];
31.
32. // move the last element into the random location
33. numbers[r] = numbers[n - 1];
34. n--;
35. }
36.
37. // print the sorted array
38.
39. Arrays.sort(result);
40. System.out.println
41. ("Bet the following combination. It'll make you rich!");
42. for (int i = 0; i < result.length; i++)
43. System.out.println(result[i]);
44.
45. System.exit(0);
46. }
47. }

java.lang.System 1.1

Java graphics api_icon