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

Arrays in Java are the most widely used data structures. The concept of Array is the same in all programming languages. In general words, we can say Java Array is a container which holds a fixed number of values.

Today, we will learn how to declare, initialize, and access the one-dimensional and multi-dimensional array.

So, don’t waste your time and start gearing up.

Java Array Tutorial

1. What is a Java Array?

An array is a homogeneous and linear collection of the same type of elements. In array, the memory allocated is contiguous. It is basically a group of similar variables that are referred under a common name. It is dynamically allocated.

Arrays are treated as Java objects so, their length can found using member length, while in C/C++ sizeof is used. The variables of Java arrays can declare like any other variable, i.e. after the datatype. The indexing of the array starts from zero. In Java, the size of an array can only specify by int type and no other type.

In Java, when a primitive data type is stored than the actual values are stored at the memory locations while when objects are stored than actual objects are stored in heap segments.

memory Allocation in Java Array

2. How to Declare, Initialize, and Access Array in Java?

2.1 Declaration of 1D Array

One-dimensional array in Java is usually declared as

datatype variablename[];

OR

datatype[] variablename;

It has two parts – first being the type which declares the element type of the array.

But first, let’s revise Java Syntax for better understanding.

Syntax

// both are valid declarations
int intArray[];
or
int[] intArray;

2.2 Instantiating an Array in Java

The general form of an array is

variablename = new datatype [size];

Here size specifies the number of elements while variablename specifies the name of the array.

Syntax

int intArray[];    //declaring array
intArray = new int[20];  // allocating memory to array

Enhance your knowledge with Literals in Java

2.3 Array Literal

When the size of the array is already known to us, then we can use the array literals.

Syntax

// Declaring array literal
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

2.4 Accessing Array Elements using for Loop

All the elements can access via for loops in Java, an element can access via index of the array, it starts from zero and ends at a total number of elements -1.

Syntax

// accessing the elements of the specified array
for (int iterator = 0; iterator < arr.length; iterator++)
  System.out.println("Element at index " + iterator +" : "+ arr[iterator]);

Example 

// Java program to illustrate creating an array of integers 
package com.dataflair.arrays;

public class ArrayDemo1 {
  public static void main (String[] args)
  { 
    // declares an Array of integers.
    int[] arrVar;
    // allocating memory for 5 integers.
    arrVar = new int[5];
    // initialize the first element of the array
    arrVar[0] = 11;
    // initialize the second element of the array
    arrVar[1] = 15;
    //so on...
    arrVar[2] = 18;
    arrVar[3] = 25;
    arrVar[4] = 32;
    // accessing the elements of the specified array
    for (int iterator = 0; iterator < arrVar.length; iterator++)
      System.out.println("Element at index " + iterator +" : "+ arrVar[iterator]);
  }
}

Output-array-demo-1

one dimensional Array in Java

2.5 Array of Objects

An array of objects is just like an array of a data type in Java.

Syntax

Employee[] arr = new Employee[7]; //employee is a user-defined class

Example

// Java program to illustrate creating an array of objects
package com.dataflair.arrays;

class Employee
{
  public int emp_id;
  public String emp_name;
  Employee(int emp_id, String emp_name)
  {
    this.emp_id = emp_id;
    this.emp_name = emp_name;
  }
}
public class ArrayOfObject {
  public static void main (String[] args)
  {
    Employee[] employeeArray;
    employeeArray = new Employee[5];
    employeeArray[0] = new Employee(1,"Ayushi");
    employeeArray[1] = new Employee(2,"Renuka");
    employeeArray[2] = new Employee(3,"Kushal");
    employeeArray[3] = new Employee(4,"Animesh");
    employeeArray[4] = new Employee(5,"Bhumika");
    for (int i = 0; i < employeeArray.length; i++)
    System.out.println("Element at " + i + " : " +employeeArray[i].emp_id +" "+ employeeArray[i].emp_name);
  }
}

Output-array-of-object

3. Java Multidimensional Array

Multi-dimensional arrays are basically arrays of arrays, they are also called Jagged arrays in java.

Syntax

int[][] intArray = new int[10][20]; //a 2D array or matrix 

int[][][] intArray = new int[10][20][10]; //a 3D array

Example

package com.dataflair.arrays;

public class MultiDimensionalArray 
{
  public static void main(String args[])
  {
    // declaring and initializing 2D array
    int arrVar[][] = { {1,2,3},{4,5,6},{7,8,9} };
    // printing 2D array
    for (int iterator1=0; iterator1< 3 ; iterator1++)
    {
      for (int iterator2=0; iterator2< 3 ; iterator2++)
      {
        System.out.print(arrVar[iterator1][iterator2] + " ");
      }

    }
  }
}

Output-multi-dimensional-array

Flow of Multi dimensional Array in Java

3.1 Passing Array to Method

Passing Array to Method is required when we want to transfer a large amount of data between to methods. This concept passes objects by reference.

Do you know the difference between Method Overloading and Overriding in Java?

Example

// Java program to demonstrate passing of array to method
package com.dataflair.arrays;
public class PassingArraytoMethod {
  // Driver method
  public static void main(String args[])
  {
    int arrVar[] = {1,2,3,4,5}; 
    // passing array to method arraySum
    arraySum(arrVar); 
  }
  public static void arraySum(int[] arrVar)
  {
    // getting arraySum of array values
    int arraySum = 0; 
    for (int iterator = 0; iterator < arrVar.length; iterator++)
      arraySum+=arrVar[iterator]; 
    System.out.println("Sum of array values : " + arraySum);
  }
}

Output-passing-array-to-method

3.2 Returning Array from Method

We can also return an array from a method. Following program shows how to return an array from method arrayMethod.

//Java program to demonstrate return of array from method
package com.dataflair.arrays;

public class ReturningArrayfromMethod {
  // Driver method
  public static void main(String args[])
  {
    int arr[] = arrayMethod(); 
    for (int iterator = 0; iterator < arr.length; iterator++)
      System.out.print(arr[iterator]+" ");
  }
  public static int[] arrayMethod()
  {
    // returning  array
    return new int[]{8,7,6};
  }
}

Output-Returning Array from Method

Java Quiz

4. Cloning of Array

4.1 Cloning of one-dimensional array

In a single-dimensional array, a ‘deep copy’ creates that is clones of the original elements or reference elements creates.

Example

// Java program to demonstrate cloning of one-dimensional arrays
package com.dataflair.arrays;

public class CloningOfArray {
  public static void main(String args[])
  {
    int intArray[] = {1,2,3};
    int cloneArray[] = intArray.clone();
    // will print false as deep copy is created for one-dimensional array
    System.out.println(intArray == cloneArray);
    for (int iterator = 0; iterator < cloneArray.length; iterator++)
    {
      System.out.print(cloneArray[iterator]+" ");
    }
  }
}

Output-cloning-of-array

1D array Cloning in Java

4.2 Cloning of multi-dimensional array

In a multi-dimensional array in java when cloning is done a ‘shallow copy’ is created that is, it creates only a single Java new array for every reference array, but subarrays share.

Multi-dimensional Array in Java

Example

// Java program to demonstrate cloning of multi-dimensional arrays
package com.dataflair.arrays;

public class CloneArrayDemo {
  public static void main(String args[])
  {
    int intArray[][] = {{1,2,3},{4,5}}; 
    int cloneArray[][] = intArray.clone();
    // will print false
    System.out.println(intArray == cloneArray);
    // will print true as shallow copy is created i.e. sub-arrays are shared
    System.out.println(intArray[0] == cloneArray[0]);
    System.out.println(intArray[1] == cloneArray[1]);
  }
}

Output-Cloning of Multi - dimensional Array

5. Summary

The aim of this Java array tutorial is complete. Now, you know how to declare and instantiate an array. In addition, you learned how to access array elements using for loop. At last, how to clone one dimensional and multi-dimensional arrays.

Hope, you liked the article. Please share your experience in the comment box!

Let’s discuss another Data Structure – Strings in Java

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.