Introduction To Java Arrays And Related Concepts

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 7, 2024

This Tutorial Introduces the Concept of Arrays in Java. We have Also Introduced Related Topics like Length, Datatypes, Cloning, Copying, Sorting, etc. under Java Arrays:

In programming, you always deal with data. Data needs to be stored in memory locations and in order to access it from time to time and process accordingly, it has to be given some name. This is done by variables.

Thus, if you want to store value 10 in memory, you will declare a variable of type int and store the value as int num = 10;

Java Arrays – Introduction

Now suppose your program requirement is such that you need 10 variables of type int.

In this case, you will have to declare 10 variables of type int as follows:

int a1;
int a2;
int a3;
int a4;
int a5;
int a6;
int a7;
int a8;
int a9;
int a10;

The above declarations will put the unnecessary burden of maintenance on the programmer. Instead of declaring so many variables, how about declaring a single variable and then have all these 10 values assigned to this variable? This is what we are going to do when we define an array and assign values to it.

Let’s begin with arrays in Java.

Java Array

Arrays are nothing but a data structure that is used to hold the data elements of the same type in a sequential fashion. From the above example, you can change the definition of ten variables into a single variable and store all the ten values using subscripts.

Let us do it in the below given way:

A[0] = 1;
A[1] = 2;
A[2] = 3;
A[3] = 4;
A[4] = 5;
A[5] = 6;
A[6] = 7;
A[7] = 8;
A[8] = 9;
A[9] = 10;

We have stored all ten values in index-based variable. The first index starts from 0. So the first value is at 0th index and the last value is at 9th index. These indices are also called Subscripts.

In the computer memory, the above Array A will be represented as:

Representation of Array A

Now we can define an array as a variable that is a collection of elements of the same data type and stored at contiguous memory locations. The size of an array is specified at the time of declaration and hence the size is fixed.

The arrays that we are going to discuss in this tutorial are Fixed-size or Static arrays. Java also supports dynamic arrays called “ArrayList” whose size can be altered on the fly. We will discuss ArrayList in detail later.

Some of the characteristic of Arrays in Java are listed below:

  • In Java, an Array is an object instantiated from a dynamically generated class.
  • Internally, Java array implements Serializable and Cloneable interfaces.
  • Java array also has object class as its parent class.
  • You can store built-in and derived type values in Java arrays.
  • You can get the length of an array using length member and not sizeof like in C/C++.
  • Java allows single as well as multi-dimensional arrays.

In this tutorial, we will introduce all the array concepts to the reader that we are going
to cover in this series on Java Arrays.

Let’s start!!

Java Array – Creation & Initialization

Arrays need to be created to use them in the program. Creating arrays includes specifying the data type of elements that the array is going to hold as well as the number of elements the array is going to contain.

We will discuss creating arrays in various ways and also in different methods using which we can initialize arrays.

An example of one of the methods used for array creation and initialization is given below.

public class Main
{
       public static void main(String[] args) {
                int[] myArray;
                myArray = new int[5];
                myArray[0] = 1;
                myArray[1] = 3;

                System.out.println("myArray[0]:" + myArray[0]);
                System.out.println("myArray[1]:" + myArray[1]);
                System.out.println("myArray[2]:" + myArray[2]);
                System.out.println("myArray[3]:" + myArray[3]);
                System.out.println("myArray[4]:" + myArray[4]);
        }
}

Output:

Java Array - Creation & Initialization

In this program, we have declared an int array and then instantiated it using new. Then we have initialized elements at indices 0 and 1 with values 1 and 3 respectively.

Finally, we print all the elements of the array. Note that the elements we did not initialize are having default values as 0 since the type of array is int.

Print Elements In Java Array

When arrays are used in programs, they are bound to be displayed. To display array elements, we employ special methods like for loop, forEach loop, toString method of Arrays class, etc. This topic includes all the various methods used for printing array elements.

Given below is a program that uses the toString method of ‘Arrays’ class to print array elements.

import java.util.*;
public class Main
{
       public static void main(String[] args) {
                int[] myArray;
                myArray = new int[5];
                myArray[0] = 1;
                myArray[1] = 3;

                System.out.println("Array Elements : " + Arrays.toString(myArray));
        }
}

Output:

Print Elements in Java Array

Length Of Array In Java

The length of an array indicates the number of elements present in the array. Unlike C/C++, where we use ‘sizeof’ operator to get the length of the array, Java array has ‘length’ property. We will explore more on this property later.

Given below is the program that displays the length of an Array.

import java.util.*;
public class Main
{
        public static void main(String[] args) {
             int[] myArray = {1,3,5,7,9,11};
             System.out.println("Size of the given array : " + myArray.length);
        }
}

Output:

Length of Array in Java

In this program, we have initialized the array using array literal and then using the length property we display the size/length of the array.

Java Array Data Types

You can have arrays of all data types. In this topic, we will explore arrays with different data types and their definitions.

In the below program, we have defined int and string type arrays and displayed their respective contents.

import java.util.*;
public class Main
{
        public static void main(String[] args) {
        int[] myArray = {1,3,5,7,9,11};

        String[] strArray = {"one","two","three","four","five"};

        System.out.println("Elements of int array : " + Arrays.toString(myArray));
        System.out.println("Elements of String array : " + Arrays.toString(strArray));
        }
}

Output:

Java Array Data types

Adding An Element To An Array

The addition of an element to the array is an important operation. The arrays in Java are static and of fixed length. Hence, you need to provide a specific set of operations to add a new element to the array. The various methods of adding an element to the array will be discussed here.

One of the methods of adding an element to the array is by using ArrayList as the intermediate structure. We convert the array to ArrayList. Then we add the element to the ArrayList and change the ArrayList back to array.

The program below shows this implementation.

import java.util.*;

  class Main {

     public static void main(String[] args)
    {
        int n = 10;
        int i;

        Integer intArray[]
            = { 1, 2, 3, 4, 5 };

        System.out.println("Original Array:\n" + Arrays.toString(intArray));

        int num = 10;

        List<Integer>intlist = new ArrayList<Integer>(Arrays.asList(intArray));

        intlist.add(num);

        intArray = intlist.toArray(intArray);

        System.out.println("\nArray after adding " + num + "\n" + Arrays.toString(intArray));
    }
}

Output:

Adding an element to an Array

Remove/Delete An Element From An Array

Removing an element from an array is also another major operation. Java doesn’t directly allow us to remove an element. So we employ other options to do this.

Given below is the implementation of one of the methods to remove the element from an array using an ArrayList.

import java.util.*;
importjava.util.stream.*;

  class Main {

     public static void main(String[] args)
    {
        int[] tensArray = { 10,20,30,40,50};

        System.out.println("Input Array: "+ Arrays.toString(tensArray));

        int index = 1;

        System.out.println("Index to be removed: " + index);

        if (tensArray == null || index < 0 || index >= tensArray.length) {

            System.out.println("No element to delete");
        }

        List<Integer>tensList = IntStream.of(tensArray).boxed().collect(Collectors.toList());

        tensList.remove(index);

        tensArray = tensList.stream().mapToInt(Integer::intValue).toArray();

        System.out.println("Array after deleting element at "+ index +
        ":\n"+ Arrays.toString(tensArray));
    }
}

Output:

Remove Delete an element from an Array

Here, we first convert the array to ArrayList and then remove the element using the ArrayList method remove. After that, we convert ArrayList back to the array and output the changed array.

Copying An Array In Java

We will discuss some of the operations to copy array elements from one array to another. We will also discuss the shallow and deep copying of arrays.

One such method is copyOf () method of the Arrays class of java.util package.

import java.util.*;
public class Main
{
       public static void main(String[] args) {
              int[] intArray = {10,15,20,25,30,35,40};
              int array_len = intArray.length;
              System.out.println("Original Array:" + Arrays.toString(intArray));

              int[] copy_intArray = Arrays.copyOf(intArray, array_len);
              System.out.println("Copied Array:" + Arrays.toString(copy_intArray));
      }
}

Output:

Copying an Array in Java

The ‘copyOf’ method of Arrays class copies the array specified as an argument along with its length to another array.

Cloning An Array In Java

You can also make a clone of an array in Java. Java provides a method for this in the ArrayUtils package. We will explore more on cloning here.

Let’s implement a simple example that clones an array in Java.

import java.util.*;
class Main
{     
    public static void main(String args[])  
    {
         int num_Array[] = {5,10,15,20,25,30};
         int clone_Array[] = num_Array.clone();

         System.out.println("Original num_Array:" + Arrays.toString(num_Array));

         System.out.println("Cloned num_Array:"+ Arrays.toString(clone_Array));

    }
}

Output:

Cloning an Array in Java

Thus, cloning is just copying using a different method.

Sorting Arrays In Java

Sorting array elements or ordering them in ascending or descending order is one of the important operations. Most of the applications need their data to be sorted. Java provides a filter sort for arrays. We will discuss this in detail under sorting.

Following is a simple example of sorting an array in Jave using Arrays.sort () method.

import java.util.Arrays;

public class Main
{
     public static void main(String[] args)
    {
         int[] num_Array = {115,32,56,78,94,108,100,63};
         System.out.println("Original Array: " + Arrays.toString(num_Array));

         Arrays.sort(num_Array);

         System.out.println("Sorted Array: " + Arrays.toString(num_Array));
    }
}

Output:

Sorting Arrays inJava

As shown above, the sort method of Arrays class sorts the array elements in ascending order.

Reverse An Array In Java

Reversing the sequence of elements is also not provided by arrays. Just like remove, we have to do some turnaround and achieve the results. In this topic, we will see the methods to reverse an array.

The following program shows the implementation of Reversing an array.

import java.util.*;

public class Main {

    public static void main(String[] args)
    {
        Integer [] even_Arrayr = {2,4,6,8,10};
        System.out.println("Original Array:" + Arrays.asList(even_Arrayr));
        Collections.reverse(Arrays.asList(even_Arrayr));
        System.out.println("Reversed Array:" + Arrays.asList(even_Arrayr));
    }
}

Output:

Reverse an Array in Java

ArrayIndexOutOfBounds Exception

When you try to access array elements beyond the specified length or a negative index, the compiler throws ‘ArrayIndexOutOfBounds’ exception. We will explore more about this exception in our related topic.

import java.util.ArrayList;
public class Main
{
    public static void main(String[] args)
    {
        ArrayList<String>myList = new ArrayList<>();
        myList.add("one");
        myList.add("two");
        System.out.println(myList.get(2));
    }
}

Output:

ArrayIndexOutOfBoundsException

In the above program, we have an ArrayList with two entries and we try to get the entry at index 2 that is not existing. Hence the program gives IndexOutofBounds Exception.

Java String Array & Various Methods

Among all the data types supported by Java, String is the most important one. Hence String type array also deserves a special discussion. As the data contained in a string array is mostly text, there are various methods provided to manipulate the text.

import java.util.ArrayList;
public class Main
{
    public static void main(String[] args)
    {
         String[] rgb = {"Red", "Green", "Blue"};

         System.out.println("The string array elements:");
         for (String item: rgb)
        {
            System.out.print(item + " ");
        }
    }
}

Output:

Java String Arrays

This is a basic program for string array. We have just declared a string array and displayed its contents using the forEach loop.

Multi-Dimensional Arrays In Java

So far we have seen only one-dimensional arrays. Java also supports multidimensional arrays having elements mostly arranged in rows and columns. Arrays in Java get more complex as each element of the array can contain another array.

We will explore multidimensional arrays in Java along with their specific operations here.

Let’s implement an example of a two-dimensional array.

class Main
{
    public static void main(String args[])
    {
        // declaring and initializing 2D array
        int array_2d[][] = { {1,2,3},{4,5,6},{7,8,9} };

        System.out.println("The two-dimensional array is as follows:");
        for (int i=0; i< 3 ; i++)
        {
            for (int j=0; j < 3 ; j++)
                 System.out.print(array_2d[i][j] + " ");

            System.out.println();
        }
    }

Output:

Multi-Dimensional Arrays in Java

Java Array Of Objects

Apart from storing primitive types, java arrays can also store objects. In this topic, we will explore some examples of an array of objects.

One example is given below.

class Main{
   public static void main(String args[]){
                Test testobj[] = new Test[2] ;
                testobj[0] = new Test();
                testobj[1] = new Test();
                testobj[0].setData(1,3);
                testobj[1].setData(2,4);
                System.out.println("For Array Element 0 (testobj[0]):");
                testobj[0].displayData();
                System.out.println("For Array Element 1 (testobj[1]):");
                testobj[1].displayData();
    }
}
class Test{
                int val1;
                int val2;
                public void setData(int c,int d){
                                val1=c;
                                val2=d;
                 }
                public void displayData(){
                                System.out.print("val1 ="+val1 + "; val2 ="+val2 + "\n");
                }
}

Output:

Java Array of Objects

We can have arrays containing elements as objects. In the above program, we have an array of objects of class Test. We individually call member functions for each object to set and display the values.

Return An Array In Java

In the same way, in which we return a variable from any method, we can return an array too. Similarly, we can pass an array to a method. Both these possibilities will be discussed with examples here.

Usually, a reference to the array is passed to/from a method.

The following program demonstrates the Return of an array in Java.

class Main {
    static int[] add_sub(int val1, int val2)
    {
         int[] result = new int[2];
         result[0] = val1 + val2;
         result[1] = val1 - val2;

         return result;
    }
    public static void main(String[] args)
    {
         int[] result = add_sub(10, 5);
         System.out.println("val1 + val2 = " + result[0]);
         System.out.println("val1 - val2 = " + result[1]);
    }
}

Output:

Return an Array in Java

In the above program, we perform two operations i.e. addition and subtraction of two numbers. The result of each operation is stored as an element in the array. Then the entire array reference is returned to the calling function.

Java Array Class

The Java array class is a class from java.util package that provides the functionality to manipulate arrays. It provides many functions like copying an array, sort, converting an array to string, etc.

Java Generic Array

We have already seen generics in Java which are type – independent entities. Java arrays can be generic in which they can be defined as independent of types. But the generic code is not available when the byte code is generated and thus it is difficult to deduce the type of element, the array will be holding at runtime.

Thus instead of arrays, we switch to lists from Java collections framework whenever generics are required.

However, we can also have a generic-like array structure by employing one or more methods. Here, we will explore these methods.

An example of one of the methods using object arrays is given below.

import java.util.Arrays;

class Main {
             public static void main(String[] args)
             {
                 final int length = 5;

                 //integer array object from Generic_Array class
                 Generic_Array<Integer>intArray = new Generic_Array(length);

                 for (int i = 0; i < length; i++)
                            intArray.set(i, i  *  2);

                 System.out.println("Integer Array elements:" + intArray);

                 // String array object from Generic_Array class
                Generic_Array<String>strArray = new Generic_Array(length);

                for (int i = 0; i < length; i++)
                        strArray.set(i, String.valueOf((char)(i + 97)));

                System.out.println("String Array Elements:" + strArray);
           }
}
//Generic Array Class
classGeneric_Array<E> {

                private final Object[] gen_Array;
                public final int length;

                publicGeneric_Array(int length)
                {
                                gen_Array = new Object[length];
                this.length = length;
                }

                Eget(int i) {
                                final E e = (E)gen_Array[i];
                                return e;
                }

                void set(int i, E e) {

                                gen_Array[i] = e;
                }

                @Override
                public String toString() {
                                returnArrays.toString(gen_Array);
                }
}

Output:

Java Generic Array

So in the above program, we have written a generic array class with object array as an element and get/set methods to get/set array objects. We have also overridden the toString method of the Arrays class. In the Main class, we create two objects of a generic array class of type Integer and String and assign them appropriate values.

Jagged Arrays In Java

Jagged arrays are multidimensional arrays with each member array of different sizes. A Jagged array is also an example of an array of arrays.

The following program shows an example of the Jagged array.

class Main
{
    public static void main(String[] args)
    {
         int jagged_array[][] = new int[2][];

         jagged_array[0] = new int[4];

         jagged_array[1] = new int[2];

        for (int i=0; i<jagged_array.length; i++)
            for(int j=0; j<jagged_array[i].length; j++)
                jagged_array[i][j] = j+1;

        System.out.println("Two-dimensional Jagged Array:");
        for (int i=0; i<jagged_array.length; i++)
        {
            System.out.print("jagged_array[" + i + "]   ");
            for (int j=0; j<jagged_array[i].length; j++)
                 System.out.print(jagged_array[i][j] + " ");
            System.out.println();
        }
    }
}

Output:

Jagged Arrays in Java

We have a 2D array in the above program. The first array dimension is 4 while the second one is 2. The output shows the contents of both the dimensions of the Jagged array.

Arrays In Java 8

As Java 8 was a major release of Java, we will go through the changes it brought about to arrays. For Example, streams on Arrays were introduced in Java 8.

Import Array In Java

We can include additional functionality for arrays in Java by importing the ‘Arrays’ class of ‘java.util’ package.

We can also import the arrayutils package for more functionalities. You must have gained more knowledge about the import functionality from our previous examples.

Java Array API & Documentation

Java array API is a collection of all the functions that act on Java arrays. We will go through this application programming interface (API) here.

We have finally listed all the properties and methods along with their description for Java arrays. This will help readers with a quick reference.

Frequently Asked Questions

Q #1) Are Arrays primitive data types in Java?

Answer: No. Arrays are not primitive data types but arrays are container objects that hold elements of the same data type in contiguous locations.

Q #2) Are Arrays reference types in Java?

Answer: Yes. The array is a container of objects and is treated as references.

Q #3) Can you increase the size of an array in Java?

Answer: No. You declare arrays and instantiate it with size. Once specified, you cannot change the size of the array.

Conclusion

In this tutorial, we introduced you to the concept of arrays in Java. We discussed the main topics associated with Java arrays.

In our subsequent tutorials, we will explore these Array related topics in Java in detail.

Happy Learning!!

Was this helpful?

Thanks for your feedback!

Leave a Comment