SCJP Study Guide:
Declarations, Initialization and Scoping


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Array

Array

Arrays are mechanisms that allow you to treat several items with the same data type as a single collection. Java language supports single-dimensional arrays, multidimensional arrays, and jagged arrays (arrays of arrays).  A Java array is a collection of primitive types, object references, or references to other arrays. An individual value stored in an array is called an element of array. An array can store only a finite number of elements. If the number of elements in an array is zero, it is called an empty array.

You can create arrays of primitive data types, for example:

/*tells the compiler that the 
variable intArray refers to an array  
  of integer values */ 
int[] intArray; 
 /*creates
an array of 20 integers and assigns its reference to intArray */
intArray = new int[20]; 

On the first line, intArray is a variable that is capable of pointing to a single-dimensioned array of int. Initially, intArray will be set to null by default. The second line shown above allocates an array of 20 int values; all of the int are initialized to 0. The reference of this array is assgined to the variable intArray.

You can also create arrays of reference types, for example:

Integer[] integerArray; //       Declares a reference to an array 
integerArray=new Integer[20]; // Create array of 20 Integer references 
integerArray[0]=new Integer(10);//Putting values into the array

On the first line, integerArray is a variable that is capable of pointing to a single-dimensioned array of Integer references. Initially, integerArray will be set to null by default. The second line allocates an array of 20 Integer references; after the array of objects is constructed using a new operator, each of the elements of array is initialized with the default value null. Since Integer is a reference type, creating the array only creates references; the actual objects are not created at this time. The address of this array object is returned and saved in the variable integerArray. The last line, we add one Integer object into the array.

Arrays are usually a group of the same variable type that use an index number to distinguish them from each other. Elements are stored in an array in a definite order using nonnegative incremental values called the indices. An element within an array is uniquely identified by its location (a positive integer value called the index) within the array. A particular element in an array is accessed by using its index value, the first element being at index 0 and the last at index one less than the length of the array.

Declaration of Array Variable

An array declaration is very similar to a variable declaration. First the data type is given for the elements of the array following with a square brackets, then an identifier for the array. The name used to declare an array variable must be a valid identifier. The square brackets may be placed before or after the identifier of the array.

Syntax:

type[] array_name;

or

type array_name[];

Here, the type represents the data type of the elements that the array is going to hold and the square brackets (i.e., []) after the type suggests that the variable array_name refers to an array. The square brackets may be placed before or after the array_name.  However, convention discourages the second form because the brackets identify the array type, and so they should appear with the type designation, not with the array name.

As with declarations for variables of other types, the declaration for an array variable does not create an array and does not allocate any memory to contain array elements. The code must create the array explicitly and assign it to the array reference.

The array declaration statement does not create an array but only informs the compiler about the data type and the name of the array variable.

Declaring the size of the array with the following notation is illegal

int[5] intArray; // illegal declaration

Array references declared as members are initialized to null, but array references declared in methods are not initialized.

class TestArray {
    int[] arr;          // initialized to 'null'

    public static void main(String[] args) {
        int[] arr1;     // reference variable 'arr1' not initialized
        
        // compiles ok
        System.out.println("arr:" + new TestArray().arr); 
        // compile error
        System.out.println("arr1: " + arr1);
    }
}

you can assign an array a null value but you can't create an empty array by using a blank index:

int[] intArray = null;      //OK
int[] intArray = new int[]; //compile-time error

Creating an Array

You create an array explicitly using Java's new operator. In general, when creating an array, you use the new operator, plus the data type of the array elements, plus the number of elements (the length of the array) desired enclosed within brackets ? [ and ].

The array construction expression constructs an array at the run time by allocating the required memory locations to the array.  After an array construction statement is executed, the array becomes a fixed length structure capable of storing values of the specified data type. The equality operator assigns the reference of the array to the array_name.

The general syntax for creating an array is as follow:

array_name = new elementType[arraySize]

If the new statement were omitted from the sample program, the compiler would print an error like the following one and compilation would fail.

The declaration and construction of arrays can be combined in single line as shown below:

int[] intArray = new int[20];

As soon as the array is created using this form of array creation statement, its elements are automatically initialized to their default values. The table given below shows the initial value of the elements of an array:

Element type Initial value
boolean false
byte 0
short 0
int 0
long 0L
char 'u0000'
float 0.0F
double 0.0D
Object reference null

For exampe:

String[] s = new String[100]; // default values: null

boolean[] b = new boolean[4]; // default values: false

int[] i = new int[10]; // default values: 0

Note: As arrays are created only at runtime, it is legal to use a variable name specifying the size of the array instead of a constant in the array creation expression. For example, the array creation statement given earlier may take the form as shown below:

int size = 10;
int inArray = new int[size];

Access Array's Element

Once you've created an array with the new operator and the square-bracket syntax, you also use square brackets to access the individual values contained in the array. Remember that an array is an ordered collection of values. The elements of an array are numbered sequentially, starting with 0. The number of an array element refers to the elements. This number is often called the index, and the process of looking up a numbered value in an array is sometimes called indexing the array.

Every time you access an array element, the Java interpreter automatically checks that the index you have specified is valid. If you specify a negative index or an index that is greater than the last index of the array, the interpreter throws an exception of type ArrayIndexOutOfBoundsException. This prevents you from reading or writing nonexistent array elements.

Array index values are integers; you cannot index an array with a floating-point value, a boolean, an object, or another array. char values can be converted to int values, so you can use characters as array indexes. Although long is an integer data type, long values cannot be used as array indexes. This may seem surprising at first, but consider that an int index supports arrays with over two billion elements. An int[] with this many elements would require eight gigabytes of memory. When you think of it this way, it is not surprising that long values are not allowed as array indexes.

Using a long index value to access an array causes a compile error.

Array Literals

The null literal used to represent the absence of an object can also be used to represent the absence of an array. For example:

char[] s = null;

There is an array literal syntax that supports this kind of anonymous arrays (so called because they are not assigned to variables, so they don't have names). This kind of array literal looks as follows:

// Call a method, passing an anonymous array literal that contains two strings
String response = askQuestion("Do you want to quit?",
                              new String[] {"Yes", "No"});

// Call another method with an anonymous array (of anonymous objects)
double d = computeAreaOfTriangle(new Point[] { new Point(1,2),
                                               new Point(3,4),
                                               new Point(3,2) });

With this syntax, you use the new keyword and specify the type of the array, but the length of the array is not explicitly specified.

It is important to understand that the Java Virtual Machine architecture does not support any kind of efficient array initialization. In other words, array literals are created and initialized when the program is run, not when the program is compiled.

Array Initialization by Accessing its Individual Elements

Although the elements of an array are automatically initialized as soon the array is created using the new operator discussed earlier, a user can explicitly initialize the elements of the array using an array initialization expression. An element within an array can be initialized explicitly by using the index associated with it.

Syntax:

array_name[integer_expression] = value or expression;

For example,

intArray[2] = 30;

This statement initializes the third element of the array referenced by intArray with the value 30.

Array Initializer


An array initializer is a list of comma-separated values or expressions enclosed within curly braces i.e., between '{' and '}'. The array initializer is a language-supported feature to simultaneously create and initialize the elements of an array. When an array initializer is used to initialize an array, there is no need to specify the size of the array. The number of elements inside the array initializer determines the size of the array.

Syntax:

type[] array_name = {expr1, expr2,.....};

Here's an example, using a shortcut syntax for creating and initializing an array:

boolean[] answers = { true, false, true, true, false };

This statement creates an array of five boolean values, as the number of elements in the array initializer is five. The given array initializer initializes the first element of the array with the value true, the second with the value false, and so on. The reference of the array created in this expression is assigned to the array variable answers by using the equality operator. This form of array creation statements must be declared and initialized in a single line. Splitting this form in more than one line will cause a compile error. For example:

boolean[] answers = null;
answers = { true, false, true, true, false }; //compile-time error

An array can also be created using an array initializer along with the new operator as shown below:

boolean[] answers = new boolean[] {true, false, true, true, false };

This statement creates an array of boolean values in the same way as discussed earlier. Here, the keyword new is followed by the information about the type of values contained inside the curly braces. This statement can be split in more than one line, i.e., the array variable may be declared in a separate line and later initialized with the reference with the reference of the array after the array is created as shown below:

boolean[] answers;
answers = new boolean[] {true, false, true, true, false };

Getting the Size of an Array

All arrays in Java have a public final field known as length. This field is used to find the length of the array. Once an array is created, its size can be obtained by using the length field qualified by the array name along with a dot operator.

Syntax:

arrayname.length

Programmers new to the Java programming language are tempted to follow length with an empty set of parenthesis. This doesn't work because length is not a method. length is a property provided by the Java platform for all arrays. For example,

 int len1 = answers.length(); //compile-time error
 int len2 = answers.length;  // OK

The .length syntax can be used only to read the length of an array. It cannot be used to set the length of an array (because, in Java, an array has a fixed length that can never change).

Multidimensional Arrays

An array having more than one dimension is called a multidimensional array. In Java, multidimensional arrays are actually  arrays of arrays. To declare a multidimensional array variable each additional index is specified by a set of square brackets.

The most commonly used multidimensional array is a two-dimensional array. In a two-dimensional array, an element within an array is uniquely identified by a set of values representing the row index and the column index.

In order to declare a variable to refer to a two-dimensional array, two pairs of square brackets are used. Here is the Syntax of two-dimensional array:

type[][] array_name;

The left index determines the row and the right index determines the column, to use this you can refer to a particular value by specifying the indices like

You must specify the length of an array when you create it. For an array that contains subarrays, you specify the length of the primary array (the size for the leftmost dimension) when you create it but don't have to specify the length of any of the subarrays until you create them. The memory allocations for the other dimensions can be done separately.  For example,

int[][] intArrays; //declares an array variable intArrays to refer to an array of arrays of Integer
char[][] charArrays;
intArrays = new int[10][2];
charArrays = new char[10][];

Here, the first expression creates a two dimensional array conceptually having 10 rows and 2 columns. The second expression creates a two-dimensional array conceptually having 10 rows with memory locations for the columns yet to be allocated separately for each elements of the row.

You can initialize the row dimension without initializing the columns but not vice versa. For example:

int[][] intArrays = new int[][2]; //compile-time error

Arrays can contain arrays. the following code creates an array and uses an initializer to populate it with four sub-arrays.

public class ArrayOfArraysDemo {
    public static void main(String[] args) {
        String[][] cartoons =
        {
	    { "Flintstones", "Fred", "Wilma", 
              "Pebbles", "Dino" },
            { "Rubbles", "Barney", "Betty", 
               "Bam Bam" },
            { "Jetsons", "George", "Jane", 
              "Elroy", "Judy", "Rosie", "Astro" },
            { "Scooby Doo Gang", "Scooby Doo", 
              "Shaggy", "Velma", "Fred", "Daphne" }
        };

        for (int i = 0; i < cartoons.length; i++) {
	    System.out.print(cartoons[i][0] + ": ");
            for (int j = 1; j < cartoons[i].length; j++) {
	        System.out.print(cartoons[i][j] + " ");
	    }
	    System.out.println();
        }
    }
}

The output from this program is:

Flintstones: Fred Wilma Pebbles Dino
Rubbles: Barney Betty Bam Bam
Jetsons: George Jane Elroy Judy Rosie Astro
Scooby Doo Gang: Scooby Doo Shaggy Velma Fred Daphne

Notice that the sub-arrays are all of different lengths. The names of the sub-arrays are cartoons[0], cartoons[1], and so on.

Arrays of Objects

An array of objects is created in the same way as the array of primitive types. The declaration and the creation of the array of objects take the same form as the array of primitives. For example:

public class ArrayOfStringsDemo {
    public static void main(String[] args) {
        String[] anArray = { "String One", 
                             "String Two", 
                             "String Three" };

        for (String s: anArray) {
            System.out.println(s.toLowerCase());
        }
    }
}

The "String[] anArray ... " statement creates an array of string objects having three elements with the first element referencing to the string "String One", the second to the string "String Two", and the third to the string "String Three".


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |