Declaring an Array
Purpose:
- To specify the type of elements and to allocate the number of elements required by an array.
Mechanics:
<modifiers> <data type>[] <array name> = new <data type>[<array size>];or<modifiers> <data type>[] <array name>;<array name> = new <data type>[<array size>];or<modifiers> <data type>[] <array name> = {<comma separated list of initializers>};
Example:
private int[] myArray = new int[20]; // declares an array and allocates space for 20 integersorprivate int[] myArray; // declares the arraymyArray = new int[20]; // allocates the arrayorprivate int[] myArray = {1, 2, 3, 4, 5}; // creates a five element array of integers and itializes the elements to 1, 2, 3, 4, 5
Usage:
- <modifiers> is an optional space-separated list of valid modifiers.
- <data type>, either the name of a class or a base type, declares what type the array will hold references to.
- <variable name> is any valid identifier which is unique to the current scope.
- <array size> is an integer that allocates the size of the array (how many references it can hold).
- <comma-separated list of initializers> are items of the declared data type. This list initializes the size of the array to the number of initializers, and initializes the elements of the array to those initializers.
Restrictions:
- The number of elements in the array is never specified in the square brackets after the array name.
email suggestions to: cs015tas@cs.brown.edu
