Arrays in java

Array is a fundamental construct in any programming languages, which stores a fixed-size sequential collection of elements of the same type.

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.


Array Declaration

Syntax for declaring an array variable in Java

dataType[] arrayRefVar;     // preferred way
dataType arrayRefVar[];     // for accommodate C/C++ programmers, but not preferred, 

Array Instantiation

Create an array by using the new operator with syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

  • It creates an array using new dataType[arraySize];
  • It assigns the reference of the newly created array to the variable arrayRefVar.

So, we can combine: declaring an array variable, creating an array and assigning the reference of the array to the variable in one statement

dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is they start from 0 to arrayRefVar.length-1.

An array index is always a whole number and it can be a int, short, byte, or char.

Once an array is instantiated, it size cannot be changed.

Its size can be accessed by using the length field like .length. It is a java final instance field.

All java arrays implements Cloneable and Serializable.


One popular exception for java beginners is ArrayIndexOutOfBoundsException. You get this exception when you access an array with an illegal index

Java Array Default Values

After instantiate an array, default values are automatically assigned to it in the following manner.

  • byte – default value is zero.
  • short – default value is zero.
  • int – default value is zero.
  • long – default value is zero, 0L.
  • float – default value is zero, 0.0f.
  • double – default value is zero, 0.0d.
  • char – default value is null, ‘\u0000’.
  • boolean – default value is false.
  • reference types – default value is null.

Notice: one popular cause of NullPointerException is accessing a null from a java array.

Iterating a Java Array

public class IterateJavaArray {
    public static void main(String args[]) {
        int marks[] = {98, 95, 91, 93, 97};
        //java array iteration using enhanced for loop
        for (int value : marks){

Multidimensional Arrays

When a component type itself is a array type, then it is a multidimensional array.

int[] marks, fruits, matrix[];

In the above code, matrix is a multidimensional array. You have to be careful in this type of java array declaration.

Note: A clone of a java multidimensional array will result in a shallow copy.

Iterate a java multidimensional array

public class IterateMultiDimensionalJavaArray {
    public static void main(String args[]) {
        int sudoku[][] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };

        for (int row = 0; row < sudoku.length; row++) {
            for (int col = 0; col < sudoku[row].length; col++) {
                int value = sudoku[row][col];

Sort a Java array

Java api Arrays contains static methods for sorting. It is a best practice to use them always to sort an array.

import java.util.Arrays;

public class ArraySort {
    public static void main(String args[]) {
        int marks[] = { 98, 95, 91, 93, 97 };
        System.out.println("Before sorting: " + Arrays.toString(marks));
        System.out.println("After sorting: " + Arrays.toString(marks));
//Before sorting: [98, 95, 91, 93, 97]
//After sorting: [91, 93, 95, 97, 98]

Copy a Java array

The following options to copy a java array:

  • We can use the util calls Arrays. It contains copyOf method for different java types.
  • The most used class by a java beginner System has a static method to copy an array.
  • Using its clone method, you can copy a java array. If the java array is multidimensional, it will be a shallow copy.
  • Write your own for loop iterating through the java array and copy elements yourself. (least preferred).

The Arrays Class

The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

  1. public static int binarySearch(Object[] a, Object key). The array must be sorted prior to making this call.
  2. public static boolean equals(long[] a, long[] a2)
  3. public static void fill(int[] a, int val)
  4. public static void sort(Object[] a)

Leave a Reply

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