ArraysS2C Home « Arrays

In this lesson we start our investigation of objects and classes by looking at arrays and how to use them. In Java the predefined data type Array objects are used for array manipulation. Investigation of this object will give us an insight into using classes before we start to create our own.

Array Definitiongo to top of page Top

An array in Java is an object that contains a collection of values which can be a collection of primitive data types or a collection of reference variable types.

  • An array of primitives data types is a collection of values that constitute the primitive values themselves.
  • An array of reference variable types is actually a collection of pointer values which point to the memory address where each object is stored on The Heap.

Whichever variable type the array holds, primitive or reference, the array itself is still an object. In Java you can define a one dimensional array which is an object that refers to a collection of values repeated one or more times, or multi dimensional arrays which are a collection of array objects (arrays of arrays). Multi dimensional arrays may contain the same number of elements in each row or column and are known as regular arrays or an uneven number of elements in each row or column which are known as irregular arrays.

array diagram

Array Creationgo to top of page Top

Array creation is a three step process as outlined below and can be achieved using separate statements or combined into a single statement.

  1. Array declaration
  2. Array allocation
  3. Array element initialization

The following table shows the different forms of the array construct that can be used.

Construct Description
One dimensional array examples
int intArray1[];
int[] intArray2;
String strArray1[];
String[] strArray2;
Array declaration.
intArray1 = new int[4];
strArray1 = new String[5];
Array allocation.

Array elements initialized to their default value.

The new keyword is mandatory for multiple statement array creation.
for (int i=0; i<intArray1.length; i++) {
    intArray1[i] = someAssignmentValue;
}

strArray[0] = "one";
...
strArray[4] = "five";
Array element initialization using a loop.



Array element initialization using a single element.
int intArray1[] = {0, 1, 5, 8};
int[] intArray2 = {0, 8};
int intArray3[] = new int[]{5, 8};
int[] intArray4 = new int[]{5, 8, 23};

String strArray1[] = {"one", "aa", "c", "rt", "je"};
String[] strArray2 = {"one", "aa", "c", "rt", "je"};
String strArray3[] = new String[]{"one", "rt", "je"};
String[] strArray4 = new String[]{"one", "rt", "je"};
Single statement array declaration

The size of the array is calculated by the number of values that are assigned to the array and should not be specfied for single statement array creation.
Two dimensional array examples
int intArray1[][];
int[][] intArray2;
int[] intArray3[];
String strArray1[][];
String[][] strArray2;
String[] strArray3[];
Array declaration.
intArray1 = new int[2][4];
intArray2 = new int[2][];
strArray1 = new String[5][];
strArray2 = new String[5][2];
Array allocation.

Array elements initialized to their default value.

The new keyword is mandatory for multiple statement array creation.
for (int i=0; i<intArray1.length; i++) {
    for (int j=0; j<intArray1[i].length; j++) {
        intArray1[i][j] = someAssignmentValue;
    }
}

strArray[0][0] = "aa";
...
strArray[4][1] = "dd";
Array element initialization using a loop.





Array element initialization using a single element.
int intArray1[][] = { {6, 2}, {5, 22, 67} };
int[][] intArray2 = { {65, 33}, {0}, {5, 14, 71} };
int[] intArray3[] = { {65, 33}, {0}, {5, 14, 71} };

int intArray1[][] = new int[][]{ {6, 2}, {5, 22, 67} };
int[][] intArray2 = new int[][]{ {5, 33}, {0}, {5, 4, 71} };
int[] intArray3[] = new int[][]{ {1, 7}, {0, 6}, {1, 1, 4} };
Single statement array declaration

The size of the array is calculated by the number of values that are assigned to the array and should not be specfied for single statement array creation.
Multi dimensional array
type arrayName[][]...[] = new type[size1][size2]...[sizeN]Same rules as one and two dimensional arrays.

Array Notesgo to top of page Top

As you can see from the table above there is a lot of ways to create arrays in Java. There are several points about arrays shown in the table above that we will highlight again here before we go into some code examples:

  • Array indexes are zero-based.
  • When declaring an array the square brackets can appear after the type, after the array name or in the case of multi dimensional arrays a combination of both.
  • After allocation of an array, each element of the array is initialized with the default for the array type:
    • object - null
    • boolean - false
    • char - /u0000
    • integer types (byte, short, int and long) - 0
    • floating-point types (float, double) - 0.0
  • For multiple statement array creation the new keyword is mandatory.
  • For single statement array creation the size of the array is calculated by the number of values that are assigned to the array and should not be specfied.

Creating A Folder For Our Objects & Classes Source Files

As this is the first code example of a new section lets create a folder for our Objects & Classes files, in Windows this would be:

double click My Computer icon

double click C:\ drive (or whatever your local drive is)

right click the mouse in the window

from the drop down menu Select New

click the Folder option and call the folder _ObjectsAndClasses and press enter.

One Dimensional Array Examplesgo to top of page Top

Lets look at some code to illustrate the use of one dimensional arrays:


/*
  One dimensional array examples 
*/ 
public class OneDimensionArrays {

    public static void main (String[] args) {
	int intArray1[];           // Array declaration
	intArray1 = new int[4];    // Array allocation
	System.out.println("Value of position 4 (index 3) : " + intArray1[3]);
	intArray1[3] = 672;        // Array initialization  
	System.out.println("Value of position 4 (index 3) : " + intArray1[3]);
	String[] strArray1;;       // Array declaration
	strArray1 = new String[3]; // Array allocation
	System.out.println("Value of position 3 (index 2) : " + strArray1[2]);
	strArray1[2] = "fred";     // Array initialization   
	System.out.println("Value of position 3 (index 2) : " + strArray1[2]);
	String strArray2[] = {"one", "aa", "c", "rt", "je"};     // Single statement array creation   
	System.out.println("Value of position 5 (index 4) : " + strArray2[4]);
    }
}

Save, compile and run the file in directory   c:\_ObjectsAndClasses in the usual way.

run one dimensional arrays

You should see 5 lines of output as in the screenshot above. This is is our first look at the new keyword which tells the compiler to construct a new instance of the object in question. We use the zero-based index number of the array object to access elements within the array. We are printing an element of the array after the allocation step to show default initialization and the same element after we have initialized it. The last line of output displays an element after a single statement array creation step.

Two Dimensional Array Examplesgo to top of page Top

Lets look at some code to illustrate the use of two dimensional arrays:


/*
  Two dimensional array examples 
*/ 
public class TwoDimensionArrays {

    public static void main (String[] args) {
	int intArray1[][];             // Array declaration
	intArray1 = new int[3][4];     // Array allocation
	for (int i=0; i<intArray1.length; i++) {  // Array initialization using a for loop 
    	    for (int j=0; j<intArray1[i].length; j++) {
        	intArray1[i][j] = i + j;
		System.out.println("Array position: " + i + ":" + j + " = " + intArray1[i][j]);
    	    }
	}
	 // Single statement array creation
	int[][] intArray2 = new int[][]{ {5, 33}, {0}, {5, 4, 71} };
	for (int i=0; i<intArray2.length; i++) { 
    	    for (int j=0; j<intArray2[i].length; j++) {
		System.out.println("Array2 position: " + i + ":" + j + " = " + intArray2[i][j]);
    	    }
	}
    }
}

Save, compile and run the file in directory   c:\_ObjectsAndClasses in the usual way.

run two dimensional arrays

The above screenshot shows the output of a couple of two-dimensional arrays. The first regular array is created using multiple statements and initialized using two for loops; we print the elements as we initialize them. The second irregular array is created using a single statement; we then use a couple of for loops to cycle through the array printing out the element values. We are using the anArray.length code to form the loop iteration. Each array has a length variable associated with it and because arrays are zero-index based this is a perfect way of looping through all the elements of an array.

java.lang Array Exceptionsgo to top of page Top

As mentioned in the Getting Started lesson all our programs implicitly import the java.lang Package. Within this package are classes of exceptions we talk about in great detail in the Flow Control section of the site. For now we are purely interested in those exceptions that can be thrown by our arrays. Following is example code and a screenshot of the runtime error when trying to access an array with a negative array allocation:


/*
  Negative array creation
*/ 
public class NegativeArrayCreation {

    public static void main (String[] args) {
        int negativeArray[]; // Array declaration
        negativeArray = new int[-2]; // Negative array allocation
        negativeArray[0] = 672; // Array initialization  
    }
}

run negative array

As you can see when we try to run the NegativeArrayCreation class we get a NegativeArraySizeException exception.

Following is example code and a screenshot of the runtime error when trying to acess an array element outside the allocation for that array:


/*
  Out of bounds example
*/ 
public class OutOfBoundsArray {

    public static void main (String[] args) {
	String strArray[] = {"one", "aa"}; // Single statement array creation   
	System.out.println("Position 3 (index 2) : " + strArray[2]); // Access outside allocation
    }
}

run out of bounds array

As you can see when we try to run the OutOfBoundsArray class we get an ArrayOutOfBoundsException exception.

Java Documentationgo to top of page Top

As mentioned in the first section Java comes with very rich documentation. The following link will take you to the Oracle online version of documentation for the Java™ Platform, Standard Edition 6 API Specification . Take a look at the documentation for the Array class which you can find by scrolling down the lower left pane and clicking on Array. Take a look through the class so you get a feel for the documentation style and the Array class itself. You will go back to this documentation time and time again so if you haven't done so already I suggest adding this link to your browser's favourites toolbar for fast access.

Lesson 1 Complete

In this lesson we looked at the various types of array for use in Java6.

What's Next?

In the next lesson we look at class structure and syntax within our Java programs.

go to home page Homepage go to top of page Top