Declaring Arrays

The basic way to declare an array is:

That’s always the preferred way but you can also put the brackets at the end (it’s syntactically valid but discouraged):

Be careful when there’s a multiple variable declaration in a single line, because the data type of the variables will be different depending on which of both forms you use:

Creating and Initializing Arrays

Once you have an array variable, you can create the array (i.e. allocate memory for the array elements) and assign values to its elements using the basic syntax:

Apart from the basic syntax, you can also both create and initialize an array at once, using the shortcut syntax:

The anonymous creation syntax is also valid:

Two important things to remember are:

  • All array elements are always initialized to their default values: 0 or false for primitive types and null for reference types.
  • Java arrays indexes are zero-based, i.e. the first element of the array is in the position 0, the second element is in the position 1, and so on

Illegal Array Initialization

You should expect questions related to arrays in the exam. However there are two common errors that many programmers aren’t able to detect in the code examples at first sight.

First, if you specify the element values, you can’t specify the array size. For example:

The previous code doesn’t compile. It should be just like one of the following two examples:

The second is that you cannot specify the size on left hand side:

Array Type Safety

Java arrays provide you safe code at compilation time, since you specify the element type when declaring an array. For example, the following code doesn’t compile:

However there is a hole in the Java array type safety that you must know about, as you can see from the following example:

 


Leave a Reply