Arrays in Java

An array is a collection of one type of variables that can be referenced by a common name. You can create arrays of any datatype.

Creation of an array is a three step process;

  1. Declaration of Array Variable.
  2. Memory Allocation for the Array.
  3. Initialization of the Array elements

1. Declaration of Array Variable

To create an array, first you must declare a variable of the desired array type. There are two syntaxes to do it:

or

Type determines the type of each element of the array. In the example above marks is an array whose every element would be of type int.

Note that:

  • This step only creates a reference variable which will point to the actual memory location when memory for the array is allocated, until then it has the value null.
  • So after this step, it is fixed that marks would be an array of integers but no memory for the array elements have still been allocated. The value of marks is currently set to null.

It can be visualized as:

Declaration of array variable
Reference variable marks has no address assigned.

 


2. Memory-allocation for the Array

Second step in the creation of an array is to allocate memory for the array elements. It is done using a keyword new as shown below.

Here

  • type: type of each element of the array
  • size : declares the maximum number of elements, the array is deisgned to hold.

What actually happens is: new dynamically allocates the desired memory and returns its address which is assigned to the array variable. The assignment binds this array variable with the memory allocated by new.

Finally the marks array has been created and it can be visualized as the diagram below:

one dimensional array
one dimensional array

The memory locations in an array are numbered, an array of size n has indices from 0 to n-1. The marks array has size 5 and its indices are numbered from 0 to 4.


3. Initialization of the array elements

When new allocates the memory for the array, it automatically initializes them with:

  • 0 for numeric type arrays like int, double etc;
  • false for boolean arrays.
  • null for reference type arrays.

So every element in marks array holds the value 0. However, this automatic initialization is rarely useful. You have to initialize the array elements according to your need.


Accessing Array elements

Any member of the array is accessed using a number inside a pair of square brackets. So for marks array:

  • 1st member can be accessed as marks[0]
  • 2nd member can be accessed as marks[1]
  • 3rd member can be accessed as marks[2]
  • and so on.

Now, you can assign them values, read their values, do computation on them and so on.

The output is:

Note that marks is an array and marks[0], marks[1] and so on are individual elements.


Variations in declaration, memory-allocation & initialization

There are couple of variations possible in the way arrays are declared and initialized.

 

1. Variable declaration and memory allocation steps can be combined into one.

So in place of:

You can write:

Both are equivalent you can use either of them.

 

2. Variable declaration and initialization steps can be combined

The example above can be re-written as:

The step :  int[] marks = {95, 90, 85, 80, 75};  automatically assigns 95 to marks[0], 90 to marks[1] and so on.

Note that:

  • Here you don’t need to use new keyword. The memory spaces are automatically created. (Memory allocation step was not explicitly required). This method is efficient, if the array size is small.
  • You are also not required to assign size to the array. It automatically computes its size based on the number of elements supplied inside curly brackets.

Loops and Arrays

Arrays store the data members in a linear order one after the other. Their indices increase everytime by one. So traversal on entire array members is quite natural using a counter inside a loop.

The output is :

Make note of the line  total_marks = total_marks + marks[i]; , In first iteration of the loop, i=0, so marks[0] is added to the total_marks. In second iteration i=1, so marks[1] is added to the total_marks and so on upto marks[4]. After this the for loop terminates.

Here you knew the size of the array in advance which was used as the terminating condition for the loop. But you need not know this. You can use  the length attribute of the array. Every array has this, you don’t have to do any work for this. To get the size of the array you type arrayName.length . So insted of :

You could have written:

 


Processing array with for-each loop/ Enchanced for loop

for-each loop is especially designed for accessing array elements. Unlike  while, do-while and normal for loop, it:

  • doesn’t need any counter variable to traverse the array.
  • doesn’t need to know the size of the array.

It accesses every member of the array one by one starting from the first all the way upto the last element.

Its syntax is (Note only syntax differs from the for loop, rest is same as the for loop):

Where,

  • type: type of each element of the array.
  • varName: any valid Java token.
  • Collection: any storage class which stores the data as a group, like arrays.

So the above for loop can be re-written as:

In first iteration of the loop, mark has the value of marks[0], which is added to the total_marks. In second iteration, mark has the value of marks[1] which is again added to the total_marks and so on upto marks[4]. After this the for-each loop terminates.


Multidimensional Arrays

All the arrays uptil now were one dimensional, i.e. like a long chain. But you can have arrays of more than one dimension:

  • Two dimensional array :- An array of one dimensional arrays i.e. an array whose every element is a one dimensional array. A two dimensional array is also called a matrix.
  • Three dimensional array :- An array of two dimensional arrays i.e. an array whose every element is a two dimensional array.
  • Four dimensional array :- An array of three dimensional arrays i.e. an array whose every element is a three dimensional array.
  • An so on.

 

Syntax to declare a two dimensional array is:

Here is an example of two- dimensional arrays:

The output is:

 

Graphically the 2D array(Matrix) can be visualized as:

Numbers[9][10], a 9x10 matrix
Numbers[9][10], a 9×10 matrix

Jagged Array

Since a two dimensional array is an array of arrays. You can have a 2D array whose column length is variable. Such an array is called a jagged array.

The output is:

 


Passing Arrays to a method

We can pass an array to a method. This feature is quite useful when we have to do computation on a group of data. Code below computes the sum of all the elements in an array and returns it:

The output is:

 


Returning an array from a method

We can return an array from a method. This feature is quite useful when we want to return a collection of data from any method. Code below returns an array of first five even numbers:

The output is :

 


Anonymous Arrays in Java

Java allows us to create an anonymous array i.e. an array without any name. They are created using the keyword new. The general syntax to create an anonynous arrays is:

 

They are generally used along with methods as in the example below:

The output is:

 


Common Errors

  • ArrayIndexOutOfBoundsException: Java checks if an index outside the boundary of an array has been accessed. If so, it returns  ArrayIndexOutOfBoundsException. You need to fix this before you move further.

 


Miscellaneous Topics

  • Array class (java.util.Arrays): Java has a number of useful built-in methods  for arrays. Visit this link for more info.

  • Copying Array in Java :Copying an array is a frequent process. There are a number of ways to do this. Visit this link for more info.

  • Array of Objects: We can create an array of not only basic types(like int, double and char), but of objects as well. In this case the individual elements of the array store the reference to the objects. If you know about classes visit this link for more info.

 


Summary

In short, Arrays in Java has following features:

  • The length of Array is fixed. (For variable length array use ArrayList).
  • Arrays are objects. Has a comon attribute length which stores the size of the array.
  • You can have arrays of any dimension.
  • Arrays can be passed as an argument to a method and can be returned from a method.
  • They can hold almost any data type, even the reference variables of other objects.
  • You can create anonymous arrays i.e. an array without any name.
  • They are created during runtime.