Declaring Arrays
The basic way to declare an array is:
1 2 3 |
int[] array; |
That’s always the preferred way but you can also put the brackets at the end (it’s syntactically valid but discouraged):
1 2 3 |
int array[]; |
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:
1 2 3 4 |
String[] sa1, sa2; // Both variables are String arrays String sa1[], sa2; // Only sa1 is a String array, sa2 is just a String |
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:
1 2 3 4 5 6 |
array = new int[3]; // create a 3 element array array[0] = 1; // assign value 1 to the first array element array[1] = 2; // assign value 2 to the second array element array[2] = 3; // assign value 3 to the third array element |
Apart from the basic syntax, you can also both create and initialize an array at once, using the shortcut syntax:
1 2 3 |
int[] array = {1, 2, 3}; |
The anonymous creation syntax is also valid:
1 2 3 |
new int[] {1, 2, 3}; |
Two important things to remember are:
- All array elements are always initialized to their default values:
0
orfalse
for primitive types andnull
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 position1
, 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:
1 2 3 |
int ia[] = new int[2] {1, 2}; |
The previous code doesn’t compile. It should be just like one of the following two examples:
1 2 3 4 5 |
int ia[] = new int[] {1, 2} int ia2[] = {1, 2} |
The second is that you cannot specify the size on left hand side:
1 2 3 |
int ia[3] = {1, 2, 3}; |
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:
1 2 3 4 |
String[] sa = new String[10]; sa[0] = new Integer(5); // compiler error: sa can only contain Strings |
However there is a hole in the Java array type safety that you must know about, as you can see from the following example:
1 2 3 4 5 6 7 8 |
String[] sa = new String[10]; Object[] oa = sa; // the following compiles but fails at runtime, since elements // of oa are String references and not Object references oa[0] = new Integer(56); |