Java Arrays Tutorial By Example

An array is a data structure of fixed size, that can hold objects of a specific type or primitive variables. The objects are either provided by core java such as String, or defined by you the software developer. Or they can be once the eight primitive data types declared as part of the Java core language.

Arrays and Data Structures In Java

You cant change the size of the array once it has been created. Arrays can be single dimensional or they can be multi dimensional (arrays within arrays).

Arrays give random access to any element using the index position.

java arrays

An Array itself is also an object in Java. Note an Array will always be an object no matter what type of elements you define it to hold. So even if you declare

even though the elements are int primitives, the myArray array itself is still an object. So irrespective of the Array contents the array itself is still an object. Also because Java is generally type safe, it will complain if you try and put an object of a different type than the one you have declared into the Array.

Core java includes a variety of data structures that allow you to reference groups or collections of objects with a variable and you will learn or have learned to use those according to your needs. Trees, Maps and Sets are part of the Java Collections, but Arrays are a simple alternative that is a structure you will find works very similarly in a number of languages.

The arrays in java are objects that implement the Serializable and Cloneable interfaces. ( The Serializable interface indicates that an object is eligible for saving its state into a file. Implementing the Cloneable interface in your class allows use of the clone() method to make a field-for-field copy of class instances ).

One of the first places you are going to encounter an array is in the main method of a Java class.

Java primitive data types

The eight primitive data types in Java are

  • byte, -128 to 127, 8 bit
  • short, -32,768 to 32,767, 16 bit
  • int, -231 to 231-1 , 0 to 231-1 , 32 bit
  • long, -263 to 263-1, 0 to 264-1, 64 bit
  • float, single-precision 32-bit IEEE 754 floating point
  • double, double-precision 64-bit IEEE 754 floating point
  • boolean, only two possible values: true and false
  • char, single 16-bit Unicode character. Value ‘\u0000' (or 0) to '\uffff' (or 65,535 inclusive)

Note the float datatype should not be used for precise numbers such as currencies where precision is important.

Working With Arrays

Creating An Array

The first step in creating an Array is to initialise it. By declaring our variable type with square brackets, the compiler will know that we are defining an array. So if we have an animal object this is as simple as below

This gives us an Array with the variable name animals, and its able to hold 5 Animal objects. But at this point all we have is the array, the elements of the Array would be null as they have not been assigned any objects.

Populating An Array

To populate the elements of the array we need to assign some objects to them.

So at this point our Array has 2 elements populated, and the remainder of the 5 elements are null as they havent been populated.

Java also allows you to declare, initialise and populate an Array all in one hit using literal values in curly brackets as shown below

This creates a String Array for us of length 3, and with element 0 = “Tom”, element 1 = “Dick” and element 2 = “Harry”.

To create an array of integers and populate it in a similar way we can do something like:

Checking The Length Of An Array

We can check the size of an array by using the length property of the Array. For example

would give us the number of elements in the array.

Accessing Array Elements

To access the elements of an array, you need to use the array variable name, plus the index number inside square brackets. As with many things in Java, array elements count from zero onwards. So each element has an index that is one less than its position in the array. So the access the first element in an array we need index 0.

The output of the above will be

Lets put that in a junit test so that we can check the values

the output of the above is

Updating Array Elements

in the same way that we can access the elements of an array using the index, we can also use the index to change the value at that index position in the array.

In the unit test above, we first confirm that the value at index 9 was 10, then we updated the array value at index 9, and then we check the new value with an assertThat. And the output of the above is

Reading An Array In A Loop

The easiest way to loop through an array is using the for-each, which is a vary simple loop command that lets you process the elements of a collection or an array. This gives you access to the elements of the array one at a time in the loop

The result of this is to list all the elements of the array

ArrayIndexOutOfBoundsException

So what happens if you try to access an array element that doesnt exist? The Java Virtual Machine will throw an exception, ArrayIndexOutOfBoundsException. This can often occur if you arent counting the number of elements in your array correctly.

Array indexes like many indexes and positions in java start at zero, so if you start you count from one you are like to get an ArrayIndexOutOfBoundsException. Lets see an example.

If we run this junit test we get the following output but also an exception, as we are accessing the array with i+1, so we are 1 more than the index. so our last index position that we check with be 10, but as java indexes start from 0, the last one is nine so java lets us know with an error.

Leave a Comment

Your email address will not be published. Required fields are marked *