Creating Arrays

Declaring arrays merely says what kind of values the array will hold. It does not create them. Java arrays are objects, and like any other object you use the new keyword to create them. When you create an array, you must tell the compiler how many components will be stored in it. Here's how you'd create the variables declared on the previous page:

k = new int[3];
yt = new float[7];
names = new String[50];

The numbers in the brackets specify the length of the array; that is, how many slots it has to hold values. With the lengths above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. This step is sometimes called allocating the array since it sets aside the memory the array requires.

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified February 12, 1997