Java Array Tutorial – Declare, Create, Initialize, Clone with Examples

In order to understand the concept of arrays, you have to understand the real-life situation of the need for arrays.

Your birthday is coming up and you have a room full of your classmates to treat to chocolates. All they are surviving college/school with you. But you remember that you have 70 of your classmates. But, you can barely hold around 10 chocolates with both of your hands. The maximum that you can carry around is 7. So do you do round trips from your school/college to the shop till all of your friends get 1 chocolate each? No!

You decide to get one big plastic jar and put all the chocolates inside it. That way it is easier to carry all the chocolates and lower risk of spilling!

Brilliant! Arrays in Java are for the exact same purpose! Let us dive in.

Arrays in java

Keeping you updated with latest technology trends, Join DataFlair on Telegram

Arrays in Java

Arrays are a collection of data items that have the same data type and referred to by a common name. Each array element is stored in such a way that each element can be calculated by applying a mathematical formula on its index. For example, an Integer array will have all integer elements and a String array will have Strings for each element of the array.
The elements are stored in a contiguous memory location which means all the memory elements are stored one after another.

However there are some points that set the arrays in Java apart from other languages:

a. All arrays in Java are dynamically allocated.

b. In Java, the length of the array is calculated using .length.This might seem to be similar to the length() method of strings. However, the concept is that the length is a final variable which puts the length of arrays. This is however not applicable for strings as the string has a length() method to calculate the length of the strings. An array in Java is declared similarly like other variables. The only difference is that a [] is added at the
end of the declaration.

c. The size of the array must be an integer value and not short, neither long.

d. The variables inside the array start from index 0.

e. Java can also be implemented as a parameter in methods, local & static variables.

f. The superclass of arrays is an Object.

g. The interfaces Cloneable and Serializable are implemented by arrays.

h. When the arrays contain primitive datatypes they are stored in memory locations which are contiguous. However when arrays of objects are created, they are stored in heap memory.

Arrays always have indexes. These indices typically denote the position of each element in the array. Since the elements are in the contiguous format, the indexing is done from 0(the first element) till n-1 where n is the length of the array. For example, an array of length 5 would have indices ranging from 0 to 4 (5-1).

Need for Java Arrays

In today’s world memory is a very expensive resource and quality usage of memory saves a lot of money and effort. Hence, in programming when we have to store a lot of data having similar data types we can use arrays. For example, if we have to store a hundred variables each of type integer, then instead of writing “int a,b,c……..”; we can declare an array of size 100 and type int.

This way we do not have to assign a different name to all the variables and each of them can be individually accessed by their index in the array. We can simply get the 87th integer by arr[87]; where arr is the name of the array.

Java ArraysIndexOutOfBoundsException

A common mistake of all programmers while using arrays is they try to access indexes which are outside the limit. For example, if an array is of length 6 then the program can use any index of the array in between 0 and 5. But sometimes the program tries to access elements outside this range. That is when the compiler throws a ArraysIndexOutOfBoundsException error.

Java program to illustrate the ArrayIndexOutOfBoundsException:

package com.dataflair.arrayclass;
class ExceptionArrayIndex {
  public static void main(String[] args) {
    int arr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    int j;
    for (j = 0; j <= arr.length; j++) {
      System.out.println(arr[j]);
    }
  }
}

Output

1
2
3
4
5
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

Declaration of Java Arrays

Arrays are declared in a simple manner. It includes the type of the variable followed by the variable name and closed box brackets([]).
The syntax is as follows:

type var_name []
or
type[] var_name;

However, writing this code only does not allocate memory to the array. It simply informs the compiler that the array exists. In order to allow memory to the array, you need to instantiate like we did objects, by using the new keyword.

Then the syntax becomes:

type var_name [] = new type [size_of_array];

Here type is the data type of the array to be declared and the size of the array is mentioned within the square brackets.
As soon as you declare the array, all the elements within the array will be stored as the default values for that particular datatype. For example, if you declare an integer array, all the elements within the array will automatically be set to 0 which is the default value of the datatype.
However, if the datatype is a reference datatype, then the values would be set to null.

This process of allocation of memory to the array in Java renders all the arrays dynamically allocated.

Java elements can be accessed both by a for loop and a for each loop. However the elements in the array cannot be altered by using the for each loop.

Java Arrays can be declared by using literals

If all the elements of an array are known previously, then the elements can be added to an array literal

The syntax for using the array literal declaration is:

datatype <var_name>[] = new datatype[] {element1,element2,element3….element n};

Java for-each loop to iterate over arrays

Just like the for loop the for-each loop can also be used to iterate over arrays. The elements of the loop cannot be altered when accessed by a for-each loop.

Syntax:

for ( < datatype > <variable > :<collection > ) {
  //code to be executed
}

Java program to illustrate the use of for each loop:

package com.dataflair.arrayclass;
class ForEachArray {
  public static void main(String[] args) {
    int arr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    for (int i: arr) {
      System.out.println(i);
    }
  }
}

Output

1
2
3
4
5

Java program to illustrate the use of arrays in a program: 

package com.dataflair.arrayclass;
public class BasicArray {
  public static void main(String[] args) {
    System.out.println("This program illustrates declaration and use of java arrays");
    int i;

    //Declaring array literal
    int arr_lit[] = new int[] {
      69,
      666,
      420,
      117
    };

    //Declaring array object
    int arr_obj[] = new int[6];

    //Using for loop to access elements in arr_obj
    for (i = 0; i < 6; i++) {
      arr_obj[i] = i;
    }

    //using for each loop to iterate through arr_lit
    System.out.println("The array literal has values");
    for (int j: arr_lit) {
      System.out.print(j + " ");
    }
    System.out.println("");
    //using for loop to iterate over each element in arr_obj

    System.out.println("The array object has values:-");
    for (i = 0; i < 6; i++) {
      System.out.print(arr_obj[i] + " ");
    }

    //we go from 0 to the number before the length of the array
    //because arrays are indexed from 0 to n-1
    //n is the size of the array

  }
}

Output

This program illustrates the declaration and use of java arrays
The array literal has values
69 666 420 117
The array object has values:-
0 1 2 3 4 5

Memory representation of single dimensional arrays in Java

As soon as the compiler executes the code int a[] = new int[5]; First, it creates a reference variable named ‘a’. This variable points to the data that is stored in the array. The data items are contiguous and they are indexed from 0 to (length of the array -1). In this case, it is from 0 to 4.

A pictorial representation of an array in memory:

java array

Java Anonymous Arrays

While passing an array to a method, you need not set a name for the array. These arrays with no names are called anonymous arrays. They can simply be passed from the function call to the method.

Java program to illustrate the concept of anonymous arrays:

package com.dataflair.arrayclass;
class AnonymousArray {
  static void printArray(int arr[]) {
    for (int i: arr) {
      System.out.println(i);
    }
  }
  public static void main(String[] args) {
    printArray(new int[] {
      1,
      2,
      3,
      4,
      5,
      0
    });
  }
}

Output

1
2
3
4
5
0

Java Array members

Arrays are objects in a class and Array class is a direct subclass of the class Object. Hence each and every member of the array object has to follow these conditions:

a. The final variable length of the array must have either a positive value or zero.
b. Each and every member inherits all the methods of the Object class except the clone method.
c. This clone method overrides the method in Object class and does not throw any checked exceptions.

Array of Objects in Java

Remember the example we took while starting the chapter about your birthday and you carrying a box of chocolates instead of carrying each one of them by hand? Well, consider candy as a class. Now this candy has many different objects such as lollipops having various flavors
such as chocolate or vanilla.

Hence all these, instead of having individual objects of their own can be presented as an array of objects of type candy.

The syntax is the same for declaring an array of objects:
<datatype> var_name[] = new <datatype>[size];

Java program to illustrate the array of objects:

package com.dataflair.arrayclass;
public class Candy {

  //class to define candy. 
  public String candy_name;
  public String flavour;

  Candy(String cname, String flav) {
    candy_name = cname;
    flavour = flav;
  }

  public static void main(String[] args) {
    int i;
    Candy arr_obj[] = new Candy[5];
    //created five objects of candy

    arr_obj[0] = new Candy("Alpenliebe", "Vanilla");
    arr_obj[1] = new Candy("Alpenliebe", "Butterscotch");
    arr_obj[2] = new Candy("Eclairs", "Chocolate");
    arr_obj[3] = new Candy("Mars", "Chocolate");
    arr_obj[4] = new Candy("Snickers", "Chocolate");

    //declared objects in the array candy 

    for (i = 0; i < 5; i++) {
      System.out.println(arr_obj[i].candy_name + " has a flavor of " + arr_obj[i].flavour);

    }

  }

}

Output

Alpenliebe has a flavor of Vanilla
Alpenliebe has a flavor of Butterscotch
Eclairs has a flavor of Chocolate
Mars has a flavor of Chocolate
Snickers has a flavor of Chocolate

Multidimensional Arrays in Java

Arrays are not limited to one dimension only. Multiple dimensional arrays exist and are used in mathematical calculations too. These are created by each element of one array holding the reference of another array.

Two-dimensional arrays are very popular in programming. However, the JVM limits the maximum number of dimensions to be created to 255.

Syntax:

<datatype>[][]<var_name>= new <datatype>[size1][size2];
or
<datatype><var_name>[][]= new <datatype>[size1][size2];
or
<datatype>[]<var_name>[]= new <datatype>[size1][size2];

Java program to illustrate the usage of multidimensional arrays:

package com.dataflair.arrayclass;
public class DoubleDimArray {
  public static void main(String[] args) {
    //Using multidimensional array literal
    int arr_lit[][] = {
      {
        1,
        2,
        3
      },
      {
        4,
        5,
        6
      },
      {
        7,
        8,
        9
      }
    };

    //using multidimensional array object
    int val = 1;

    int matrix[][] = new int[4][4];

    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 4; j++) {
        matrix[i][j] = val;
        val++;
      }
    }
    //printing the matrix
    System.out.println("The matrix is");
    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 4; j++) {
        System.out.print(matrix[i][j] + "\t");

      }
      //adding a blank line after every row
      System.out.println("");
    }
  }

}

Output

The matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

The tab escape sequence is added for clear output.

Cloning Arrays in Java

Cloning is an intricate concept in Java. As the name suggests, the cloning of an array is the process of creating another array with the same values. However, the process of cloning is different for single-dimensional and multidimensional arrays.

1. Java Single dimensional Array Cloning

When a single-dimensional array is cloned, each and every element is copied from the original array. Note that all the elements are copied and the references are not the same. This means that the members of the array which are cloned are the same in the value but their references are different. This is known as a deep copy.

2. Java Multidimensional Array Cloning

Multidimensional arrays are arrays that contain arrays. Simply speaking each element in a multidimensional array is a reference to a different array. While cloning, a new array is created with the array elements but the subarrays are shared through references.

While cloning multidimensional arrays, only a single array is created and all the sub-arrays in it are referenced. This is known as Shallow copy.

Syntax:
<array2> = <array1>.clone();

Java program to illustrate the concept of cloning:

package com.dataflair.arrayclass;
class CloningArrays {

  public static void main(String[] args) {
    int newarr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    int clonearr[] = newarr.clone();
    for (int i: clonearr) {
      System.out.println(i);
    }
    System.out.println("Check if references are equal");
    System.out.println(clonearr == newarr);

    //cloning multidimensional arrays
    int multnew[][] = new int[][] {
      {
        1,
        2,
        3
      },
      {
        4,
        5,
        6
      },
      {
        7,
        8,
        9
      }
    };
    int clonemult[][] = multnew.clone();
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        System.out.print(clonemult[i][j] + " ");
      }
      System.out.println("");
    }
    System.out.println("Check if references to the outer array are the same. ");
    System.out.println(multnew == clonemult);
    System.out.println("Check if references of the inner array are the same. ");
    System.out.println(multnew[0] == clonemult[0]);
  }
}

Output

1
2
3
4
5
Check if references are equal
false
1 2 3
4 5 6
7 8 9
Check if references to the outer array are the same.
false
Check if references of the inner array are the same.
true

Passing arrays to a method

Arrays can be passed to a method. This enables the method to access and perform operations on the array. Various algorithms can be applied to the array once a particular method can access it.

Syntax for passing arrays to method:
method_name(name_of_array)

Returning arrays from a method

Similar to passing arrays to a function arrays can also be returned to the calling statement of the method. This enables the method to perform operations on the array and return it.

The syntax for returning arrays from the method:
return arr_name;

Java program to illustrate the passing and returning of arrays from methods:

package com.dataflair.arrayclass;
public class PassReturnArrayToMethod {
  static int[] increment1(int arr[]) {
    int i;
    for (i = 0; i < arr.length; i++) {
      arr[i] = arr[i] + 1;
    }
    return arr; //returning array from method. 
  }
  public static void main(String[] args) {
    int orgarray[] = new int[] {
      1,
      2,
      3,
      4,
      5
    }; //original array
    int retarray[] = increment1(orgarray); //passing array to method
    System.out.println("The array when incremented by 1 becomes: ");
    for (int i: retarray) {
      System.out.print(i + " ");
    }

  }

}

Output

The array when incremented by 1 becomes:
2 3 4 5 6

Array class in Java

The array class in Java is particularly useful for performing functions that are tedious to write manually. It has a lot of methods for creating and accessing Java arrays. It also includes sorting, searching, and a lot of popular functions that are frequently useful by programmers to manipulate arrays.

This is a part of the java.util package. This class inherits from the Object class.

Some of the useful methods are as below :

1. Java toString

This method converts the array to a string which can then be easily printed without using for loops. This converts the array to string form, by separating each of its elements with a comma and enclosing the array within square brackets. It enables the programmer to print the array without having to use loops.

The syntax is:
Arrays.toString(<array>);

Java program to illustrate the use of toString method:

package com.dataflair.arrayclass;
import java.util.Arrays;
class ToStringMethod {

  public static void main(String[] args) {
    int newarr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    System.out.println("The array, when passed to the toString method, is: " + Arrays.toString(newarr));
  }
}

Output

The array, when passed to the toString method, is: [1, 2, 3, 4, 5]

2. Java Binary Search

As the name suggests, the method implements a binary search algorithm and returns the index of the value that is to be searched. If the value is not found it returns (-(insertion point)-1). The insertion point is the point where the element had to be inserted in the array.

Its syntax is:
binarySearch(<array>,<element>);

Java program to illustrate the use of binarySearch method:

package com.dataflair.arrayclass;
import java.util.Arrays;
class BinarySearchMethod {

  public static void main(String[] args) {
    int newarr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    int search = 3;
    System.out.println("The array, when passed to the binarySearch method, is: " + Arrays.binarySearch(newarr, search));
  }
}

Output

The array, when passed to the binarySearch method, is: 2

3. Java Compare

This method simply compares the two arrays passed in its arguments lexicographically. This returns 0 if the arrays are the same.

The syntax is:
Arrays.compare(array1,array2)

Java program to illustrate the use of the compare method:

import java.util.Arrays;
class CompareMethod {

  public static void main(String[] args) {
    int newarr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    int newarr2[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    int search = 0;
    System.out.println("The array, when passed to the  compare method, is: " + Arrays.compare(newarr, newarr2));
  }
}

Output

The array, when passed to the compare method, is: 0

4. Java Fill

The fill method, as the name suggests, fills each of the indexes of the array with the value passed to it.

The syntax of the method is:
fill(Array, value)

Java program to illustrate the use of fill method:

package com.dataflair.arrayclass;
import java.util.Arrays;
class FillMethod {

  public static void main(String[] args) {
    int newarr[] = new int[] {
      1,
      2,
      3,
      4,
      5
    };
    Arrays.fill(newarr, 54);
    System.out.println("The array, when passed to fill method, is: " + Arrays.toString(newarr));
  }
}

Output

The array, when passed to fill method, is: [54, 54, 54, 54, 54]

5. Java equals

Java equals method returns true if both the arrays that are to be compared are equal. If not it returns false. However, the deepEquals method is useful to check whether multidimensional arrays are equal to one another(i.e it returns true if the corresponding pairs of elements are equal even in nested arrays of arbitrary depth.)

Syntax:
Arrays.equals(Object Array1,Object Array2)
Arrays.deepEqual(Object Array1,Object Array2)

Java program to illustrate the use of equals and deepEquals:

package com.dataflair.arrayclass;
import java.util.Arrays;
class Equals {

  public static void main(String[] args) {

    Integer arr1[] = new Integer[] {
      1,
      2,
      3,
      4,
      5
    };
    Integer arr2[] = new Integer[] {
      1,
      2,
      3,
      4,
      5
    };

    System.out.println("Is arr1 and arr2 equal? " + Arrays.equals(arr1, arr2));
    System.out.println("Is arr1 and arr2 equal? " + Arrays.deepEquals(arr1, arr2));

    Integer mat1[][] = new Integer[][] {
      {
        1,
        2,
        3
      },
      {
        4,
        5,
        6
      },
      {
        7,
        8,
        9
      }
    };
    Integer mat2[][] = new Integer[][] {
      {
        1,
        2,
        3
      },
      {
        4,
        5,
        6
      },
      {
        7,
        8,
        9
      }
    };
    System.out.println("Is mat1 and mat2 equal? " + Arrays.equals(mat1, mat2));
    System.out.println("Is mat1 and mat2 equal? " + Arrays.deepEquals(mat1, mat2));

  }
}

Output

Is arr1 and arr2 equal? true
Is arr1 and arr2 equal? true
Is mat1 and mat2 equal? false
Is mat1 and mat2 equal? true

Notice that the equal method doesn’t think that matrix 1 and 2 are equal because it cannot check arrays of arbitrary depth.

6. Java Sort

The sort method, as the name suggests, sorts the array elements in ascending or descending order. This method does not return any value.

The syntax of this method is:
Arrays.sort(Array,startIndex,endIndex,Comparator);

Java program to illustrate the use of the sort method:

package com.dataflair.arrayclass;
import java.util.Arrays;
import java.util.Collections;
class ArraySort {

  public static void main(String[] args) {

    Integer arr1[] = {
      3,
      2,
      1,
      4,
      5
    };
    Integer arr2[] = {
      6,
      4,
      32,
      2,
      1
    };
    Arrays.sort(arr1);
    Arrays.sort(arr2, Collections.reverseOrder());
    //we are using Integer instead of int because Collections does not work with primitive datatypes.
    System.out.println("The array arr1 in ascending order is " + Arrays.toString(arr1));
    System.out.println("The array arr2 in descending order is " + Arrays.toString(arr2));
  }
}

Output

The array arr1 in ascending order is [1, 2, 3, 4, 5]
The array arr2 in descending order is [32, 6, 4, 2, 1]

Advantages and Disadvantages of Arrays in Java

Arrays are extensively useful in distributed systems and to store data in a linear manner. The advantage of this data structure is that the data members can be easily accessed and indexed. Any element in the array can be randomly accessed.

However, there is one drawback that the size of the array is fix. It doesn’t change during runtime. This drawback can be overcome by using collections such as linked lists about which we will learn in future articles.

Summary

We learned about a very important concept of Java in this article called arrays. Arrays are extremely useful in programming as it saves a lot of space. We also learned about some useful methods in the Java class Array.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.