Declaring Arrays

Like all other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. One array cannot store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:

int[] k;
float[] yt;
String[] names;

This says that k is an array of ints, yt is an array of floats and names is an array of Strings. In other words you declare an array like you declare any other variable except that you append brackets to the end of the type.

You also have the option to append the brackets to the variable instead of the type.

int k[];
float yt[];
String names[];

However, unlike in C, you cannot include the length of the array in the declaration. The following is a syntax error:

int k[3];
float yt[7];
String names[100];
int k[];
float yt[];
String names[];

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 12, 2003