Creating Arrays

Data structures are a key feature in any programming language, enabling pieces of data to be stored and processed together as a single object.  Java provides several categories of data structures, such as arrays and collections.

An array is a non-resizable data structure that stores multiple objects or primitive types together as a single object.  It is a sectioned container where each section can hold a single array element.  All of the array elements are the same type and are numbered with a unique number starting at zero, called the array index.

An array must be declared and initialized before it can be used to store data.  Arrays are declared by placing a set of square brackets [] immediately after a datatype, followed by the name that will reference the array.

Datatype[] arrayName;

The square braces can also be placed after the name of the variable:

Datatype arrayName[];

To create an array of integers called numbers, it would be:

int[] numbers;

An array can also be an array of objects, such as an array of strings.

string[] words;

Declaring the array doesn’t make it usable.  It must also be initialized.  Creating the actual array in memory doesn’t occur until it is initialized.  After declaration, the keyword new will initialize the array.  This is where it is necessary to specify how large the array should be.

int[] numbers;
numbers= new int[10];

This declares the variable numbers to be an array filled with integers.  It then creates the new integer array, of size 10, and assigns it to the variable numbers.  It can be done similarly with an array of objects.

String[] words = new String[5];

A newly initialized array is empty, meaning that all its elements are null.  The size of the array cannot be increased or decreased after being initialized.  Arrays cannot have a negative size, attempting to do so will throw an exception.

After the array is initialized, it can be used to store data.  Values are assigned to individual array elements, which are accessed using the array name and the index number of the array element.  To store a value in the first element of the numbers array:

numbers[0]=2;

Since arrays are zero based, an integer array with a size of ten has array elements 0-9.  Storing a value in element 10 or higher would cause an exception to be thrown for this array.  The highest element in an array index is always one less than the total size of the array.

An array of primitive types contains values, while an array of objects contains references to the objects in memory.

Java does provide a mechanism that allows an array to be created and populated with only one line of code.  To create a populated array of strings:

String[] beatleNames = {“John”, “Paul”, “George”, “Ringo”};

This is the equivalent to:

String[] beatleNames;
beatleNames = new String[4];
beatleNames[0]=”John”;
beatleNames[1]=”Paul”;
beatleNames[2]=”George”;
beatleNames[3]=”Ringo”;

This Site

Login

Latest News