Chapter 1) Declarations and Access Control

Objective 1, Creating Arrays

Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms, both for declaration and for initialization.


Arrays in Java are similar in syntax to arrays in other languages such as C/C++ and Visual Basic. However, Java removes the feature of C/C++ whereby you can bypass the [] style accessing of elements and get under the hood using pointers. This capability in C/C++ , although powerful, makes it easy to write buggy software. Because Java does not support this direct manipulation of pointers, this source of bugs is removed.

An array is a type of object that contains values called elements. This gives you a convenient bag or holder for a group of values that can be moved around a program, and allows you to access and change values as you need them. To give a trivial example you could create an array of Strings, each one containing the names of members in a sports team. The array can be passed into methods that need to access the names of each team member. If a new member joins the team, one of the old names can be modified to become that of the new member. This is much more convenient than having an arbitrary number of individual variables such as player1, player2, player3 etc Unlike variables which are accessed by a name, elements are accessed by numbers starting from zero. Because of this you can "walk" through an array, accessing each element in turn.

Arrays are very much like objects, they are created with the new keyword, and have the methods of the great grandparent Object class. Arrays may store primitives or references to objects.

Every element of an array must be of the same type The type of the elements of an array is decided when the array is declared. If you need a way of storing a group of elements of different types, you can use the collection classes which are a new feature in the Java2 exam, and are discussed in section 10. You can store an array of object references, which you can access, extract and use like any other object reference.

Declaration without allocation

The declaration of an array does not allocate any storage, it just announces the intention of creating an array. A significant difference to the way C/C++ declares an array is that no size is specified with the identifier. Thus the following will cause a compile time error

int num[5];

The size of an array is given when it is actually created with the new operator thus

int num[];
num = new int[5];

You can think of the use of the word new as similar to the use of the word new when initialising a reference to an instance of a class. The name num in the examples is effectively saying that num can hold a reference to any size array of int values.

Simultaneous declaration and creation

This can be compressed into one line as

int num[] = new int[5];

Also the square brackets can be placed either after the data type or after the name of the array. Thus both of the following are legal

int[] num;
int num[];

You can read these as either

An integer array named num

An integer type in an array called num.

You might also regard it as enough choice to cause confusion

Java vs C/C++ arrays

Java arrays know how big they are, and the language provides protection from accidentally walking off the end of them.

This is particularly handy if you are from a Visual Basic background and are not used to constantly counting from 0. It also helps to avoid one of the more insidious bugs in C/C++ programs where you walk off the end of an array and are pointing to some arbitrary area of memory.

Thus the following will cause a run time error,

int[] num= new int[5];
for(int i =0; i<6; i++){

The standard idiom for walking through a Java array is to use the length member of the array thus

int[] num= new int[5];
for(int i =0; i<num.length; i++){

Arrays know their own size

Just in case you skipped the C/C++ comparison, arrays in Java always know how big they are, and this is represented in the length field. Thus you can dynamically populate an array with the following code

int myarray[]=new int[10];
for(int j=0; j<myarray.length;j++){

Note that arrays have a length field not a length() method. When you start to use Strings you will use the string, length method, as in

With an array the length is a field (or property) not a method.

Java vs Visual Basic Arrays

Arrays in Java always start from zero. Visual Basic arrays may start from 1 if the Option base statement is used. There is no Java equivalent of the Visual Basic redim preserve command whereby you change the size of an array without deleting the contents. You can of course create a new array with a new size and copy the current elements to that array.

An array declaration can have multiple sets of square brackets. Java does not formally support multi dimensional arrays, however it does support arrays of arrays, also known as nested arrays.

The important difference between multi dimensional arrays, as in C/C++ and nested arrays, is that each array does not have to be of the same length. If you think of an array as a matrix, the matrix does not have to be a rectangle. According to the Java Language Specification


"The number of bracket pairs indicates the depth of array nesting."

In other languages this would correspond to the dimensions of an array. Thus you could set up the squares on a map with an array of 2 dimensions thus

int i[][];

The first dimension could be X and second Y coordinates.

Combined declaration and initialization

Instead of looping through an array to perform initialisation, an array can be created and initialised all in one statement. This is particularly suitable for small arrays. The following will create an array of integers and populate it with the numbers 0 through 4

int k[]=new int[] {0,1,2,3,4};

Note that at no point do you need to specify the number of elements in the array. You might get exam questions that ask if the following is correct.

int k=new int[5] {0,1,2,3,4} //Wrong, will not compile!

You can populate and create arrays simultaneously with any data type, thus you can create an array of strings thus

String s[]=new String[] {"Zero","One","Two","Three","Four"};

The elements of an array can be addressed just as you would in C/C++ thus

String s[]=new String[] {"Zero","One","Two","Three","Four"};

This will output the string Zero.

Default values of arrays

Unlike other variables that act differently between class level creation and local method level creation, Java arrays are always set to default values.

The elements of arrays are always set to default values wherever the array is created

Thus an array of integers will all be set to zero, an array of boolean values will always be set to false. Thus the following code will compile without error and at runtime will output 0.

public class ArrayInit{
    public static void main(String argv[]){
        int[] ai = new int[10];

By contrast with primitive variables, the following code will throw a compile time error with a message something like “variable i might not have been initialized”

ublic class PrimInit{
    public static void main(String argv[]){
    int i;


Question 1)

How can you re-size an array in a single statement whilst keeping the original contents?

1) Use the setSize method of the Array class
2) Use Util.setSize(int iNewSize)
3) use the size() operator
4) None of the above

Question 2)

You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it?

public class MyAr{
public static void main(String argv[]){
        int[] i = new int[5];

1) Compilation and output of 0
2) Compilation and output of null
3) Compilation and runtime Exception
4) Compile time error

Question 3)

You want to loop through an array and stop when you come to the last element. Being a good Java programmer, and forgetting everything you ever knew about C/C++ you know that arrays contain information about their size. Which of the following can you use?


Question 4)

Your boss is so pleased that you have written HelloWorld he she has given you a raise. She now puts you on an assignment to create a game of TicTacToe (or noughts and crosses as it was when I were a wee boy). You decide you need a multi dimensioned array to do this. Which of the following will do the job?

1) int i      =new int[3][3];
2) int[] i =new int[3][3]; 3) int[][] i =new int[3][3]; 4) int i[3][3]=new int[][];

Question 5)

You want to find a more elegant way to populate your array than looping through with a for statement. Which of the following will do this?

    end with
   2)String s[5]=new String[] {"Zero","One","Two","Three","Four"};
   3)String s[]=new String[] {"Zero","One","Two","Three","Four"};
   4)String s[]=new String[]={"Zero","One","Two","Three","Four"}; 

Question 6)

What will happen when you attempt to compile and run the following code?

public class Ardec{
    public static void main(String argv[]){
    Ardec ad = new Ardec();
    public void amethod(){
    int ia1[]= {1,2,3};
    int[] ia2 =  {1,2,3};
    int  ia3[] = new int[] {1,2,3};

1) Compile time error, ia3 is not created correctly
2) Compile time error, arrays do not have a length field
3) Compilation but no output
4) Compilation and output of 3


Answer 1)

4) None of the above

You cannot "resize" and array. You need to create a new temporary array of a different size and populate it with the contents of the original. Java provides resizable containers with classes such as Vector or one of the members of the collection classes.

Answer 2)

3) Compilation and runtime Exception

You will get a runtime error as you attempt to walk off the end of the array. Because arrays are indexed from 0 the final element will be i[4], not i[5]

Answer 3)

2) myarray.length;

Answer 4)

  3) int[][] i=new int[3][3];

Answer 5)

  3)String s[]=new String[] {"Zero","One","Two","Three","Four"};  

Answer 6

4) Compilation and output of 3

All of the array declarations are correct, if you find that unlikely, try compiling the code yourself

Other sources on this topic

The Java Language Specification

This topic is covered in the Sun tutorial at

Jyothi Krishnan on this topic at

Bruce Eckel Thinking In Java

Connecticut State University