Arrays in Java

Java Array Objects

Arrays in Java are dynamically created objects; therefore Java arrays are quite different from C and C++ the way they are created. Elements in Java array have no individual names; instead they are accessed by their indices. In Java, array index begins with 0 hence the first element of an array has index zero. The size of a Java array object is fixed at the time of its creation that cannot be changed later throughout the scope of the object. Because Java arrays are objects, they are created using new operator. When an object is created in Java by using new operator the identifier holds the reference not the object exactly. Secondly, any identifier that holds reference to an array can also hold value null. Third, like any object, an array belongs to a class that is essentially a subclass of the class Object, hence dynamically created arrays maybe assigned to variables of type Object, also all methods of class Object can be invoked on arrays. However, there are differences between arrays and other objects the way they are created and used.

It is very important to note that an element of an array can be an array. If the element type is Object or Cloneable or java.io.Serializable, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types.

Creating and Using Arrays

As it is said earlier, a Java array variable holds a reference to an array object in memory. Array object is not created in memory simply by declaring a variable. Declaration of a Java array variable creates the variable only and allocates no memory to it. Array objects are created (allocated memory) by using new operator that returns a reference of array that is further assigned to the declared variable.

Note That Java allows creating arrays of abstract class types. Elements of such an array can either be null or instances of any subclass that is not itself abstract.

Let's take a look at the following example Java array declarations those declare array variables but do not allocate memory for them.

int[] arrOfInts; // array of integers
 
short[][] arrOfShorts; // two dimensional array of shorts
 
Object[] arrOfObjects; // array of Objects
 
int i, ai[]; // scalar i of type int, and array ai of ints

For creating a Java array we first create the array in memory by using new then assign the reference of created array to an array variable. Here is an example demonstrating creation of arrays.

/* ArrayCreationDemo.java */
// Demonstrating creation of Java array objects
public class ArrayCreationDemo
{
    public static void main(String[] args)
    {
        int[] arrOfInts = new int [5]; // array of 5 ints
        int arrOfInts1[] = new int [5]; // another array of 5 ints
 
        // array of 5 ints, initializing array at the time of creation
        int arrOfInts2[] = new int []{1, 2, 3, 4, 5};
 
        //creates array of 5 Objects
        Object[] arrOfObjects = new Object[5];
        Object arrOfObjects1[] = new Object[5];
 
        //creates array of 5 Exceptions
        Exception arrEx[] = new Exception[5];
 
        // array of shorts, initializing that at the time of creation.
        short as[] = {1, 2,3, 4, 5};
    }
}

Above program declares and allocates memory for arrays of types int, Object, Exception, and short. Most importantly, you would have observed that the array index operator [] that is used to declare an array can appear as part of the type or as part of the variable. For example, int[] arr and int arr[], both declare an array arr of type int.

The placement of [] during array declaration makes difference when you declare a scalar and an array in the same statement. For an instance, the statement int i, arr[]; declares i as an int scalar, and arr as an int array. Whereas, the statement int[] i, arr; declares both i and arr as int arrays.

One more example, have a look at following declarations and you would understand the role of placement of array operator ([]) in array declaration statements.

int[] arr1, arr2[];
//is equivalent to
int arr1[], arr2[][];
 
int[] arr3, arr4;
//is equivalent to
int arr3[], arr4[];

Various Ways to Create a Java Array

In Java programming language, there are more than one ways to create an array. For demonstration, an array of int elements can be created in following number of ways.

int[] arr = new int[5];
 
int arr[] = new int[5];
 
/* In following declarations, the size of array 
 * will be decided by the compiler and will be 
 * equal to the number of elements supplied for
 * initialization of the array
 */
 
int[] arr = {1, 2, 3, 4, 5};
 
int arr[] = {1, 2, 3, 4, 5};
 
int arr[] = new int[]{1, 2, 3, 4, 5};

Java Empty Array

Java allows creating an array of size zero. If the number of elements in a Java array is zero, the array is said to be empty. In this case you will not be able to store any element in the array; therefore the array will be empty. Following example demonstrates this.

/* EmptyArrayDemo.java */
// Demonstrating empty array
public class EmptyArrayDemo
{
    public static void main(String[] args)
    {
        int[] emptyArray = new int[0];
 
        //will print 0, if length of array is printed
        System.out.println(emptyArray.length); 
 
        //will throw  java.lang.ArrayIndexOutOfBoundsException exception
        emptyArray[0] = 1; 
    }
}

As you can see in the EmptyArrayDemo.java, a Java array of size 0 can be created but it will be of no use because it cannot contain anything. To print the size of emptyArray in above program we use emptyArray.length that returns the total size, zero of course, of emptyArray.

Every array type has a public and final field length that returns the size of array or the number of elements an array can store. Note that, it is a field named length, unlike the instance method named length() associated with String objects.

You can also create an array of negative size. Your program will be successfully compiled by the compiler with a negative array size, but when you run this program it will throw java.lang.NegativeArraySizeException exception. Following is an example:

/* NegativeArraySizeDemo.java */
// Demonstrating negative-sized array
 
public class NegativeArraySizeDemo
{
    public static void main(String[] args)
    {
        /* following declaration throw a
         * run time exception 
         * java.lang.NegativeArraySizeException
         */
        int[] arr = new int[-2];
    }
}
 
OUTPUT
======
D:\>javac NegativeArraySizeDemo.java
 
D:\>java NegativeArraySizeDemo
Exception in thread "main" java.lang.NegativeArraySizeException
    at NegativeArraySizeDemo.main(NegativeArraySizeDemo.java:12)
 
D:\>

Accessing Java Array Elements

Array elements in Java and other programming languages are stored sequentially and they are accessed by their position or index in array. The syntax of an array access expression goes here:

array_reference [ index ];

Array index begins at zero and goes up to the size of the array minus one. An array of size N has indexes from 0 to N-1. While accessing an array the index parameter of the array access expression must evaluate to an integer value, using a long value as an array index will result into compile time error. It could be an int literal, a variable of type byte, short, int, char, or an expression which evaluates to an integer value.

Another important point you should keep in mind that the validity of index is checked at run time. A valid index must fall between 0 to N-1 for an N-sized array. Any index value less than 0 and greater than N-1 is invalid. An invalid index, if encountered, throws ArrayIndexOutOfBoundsException exception.

For-each Loop to Iterate Through Array Elements

Java array elements are printed by iterating through a loop. Since 1.5 Java provides an additional syntax of for loop to iterate through arrays and collections. It is called enhanced for loop or for-each loop. Use of enhanced for loop is also illustrated in Control Flow - iteration tutorial. Here is an example:

/* EnForArrayDemo.java */
// Demonstrating accessing array elements
public class EnForArrayDemo
{
    public static void main(String[] args)
    {
        int[][] arrTwoD = new int[3][];
        arrTwoD[0] = new int[2];
        arrTwoD[1] = new int[3];
        arrTwoD[2] = new int[4];
 
        for(int[] arr : arrTwoD)
        {
            for(int elm : arr)
            {
                System.out.print(elm + " ");
            }
            System.out.println();
        }
    }
}
 
OUTPUT
======
0 0 
0 0 0 
0 0 0 0 

Program EnForArrayDemo.java demonstrates two important points along with accessing array elements. First, in a two dimensional array of Java, all rows of the array need not to have identical number of columns. Second, if arrays are not explicitly initialized then they are initialized to default values according to their type (see Default values of primitive types in Java). Taking second point into consideration, we have not initializes array arrTwoD to any value. So the whole array got initialized by zeroes, because arrTwoD is of type int.

Java Array of Characters is Not a String

Readers, who come from C and C++ background may find the approach, Java follows to arrays, different because arrays in Java work differently than they do in C/C++ languages. In the Java programming language, unlike C, array of char and String are different. Character array in Java is not a String, as well as a String is also not an array of char. Also neither a String nor an array of char is terminated by \u0000 (the NUL character).

A String object is immutable, that is, its contents never change, while an array of char has mutable elements.

Last Word

This tutorial explained how to declare, initialize and use Java arrays. Java arrays are created as dynamic objects. Java also supports empty arrays, and even negative size arrays, however, empty arrays cannot be used to store elements. Java provides a special syntax of for loop called enhanced for loop or for-each to access Java array elements. Also Java arrays are not String and the same is true vice versa.

Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.