Arrays in Java

Beginners code Computer Skills Java Mobile Development Web Development

Let us discuss all the features and types of arrays in Java.

What is an Array?

An array is a collection of elements that of the same type and has a continuous memory location.

  • It is generally used to prepare a list.
  • In Java, an array is an object where we store elements of a similar data type.
  • We can store only a fixed number of elements in an array.
  • An array is index based; the first element of the array is stored at index 0.

Advantages of Array:

  • Code Optimization
    • It makes the code optimized. We can retrieve or sort data easily.
  • Random Access
    • Data can be retrieved from an index of the array directly without having to traverse the whole array.

Disadvantages of Array:

  • Size Limit
    • We can store only fixed size elements in an array.
    • It doesn’t grow its size at runtime.

To tackle this problem, Java supports the collection framework to store multiple data in a group.

Types of Array:

Singe Dimensional Array:

You can create an array in Java in 3 simple steps:

  1. Declare an array
  2. Instantiate an array
  3. Initialize an array

Declare an array:

  • Syntax:
data_type[] arrayName; 
data_type []arrayName; 
data_type arrayName[];
  • Example:
int[] arr; 
int []arr; 
int arr[];
  • In Java, we cannot specify the size of the array at the time of declaration.
  • It is done during the instantiation of the array.

Instantiate an array:

  • Syntax:
    • arrayName = new data_type[size];
  • Example,
    • arr = new int[5];
  • Memory allocation for the array is done by the new keyword.
  • At the time of memory allocation, giving the size is compulsory.
  • Once the size is defined, then it cannot be shrunk or expanded.

Initialize an array:

arr[0]=10;
arr[1]= 20;

You can also declare, initialize and instantiate an array at the same time in a single line.

int arr[] = new int[] {33,2,9,7};

  • If you are initializing the array along with the declaration as shown in the above example, then you cannot specify the size exclusively.
  • The size will now depend upon the number of elements present in the array.

Here is a working example of using arrays in Java

Objective: Write a program to initialize and display all the elements of a 1D array

import java.util.Scanner;

public class ArrayDisplay {

  public static void main(String[] args) {
    
    // initialize the array
    int arrStatic[] = new int[] {22, 45, 1, 7, 8, 9};
    
    // display array elements using for each loop
    System.out.println("elements of the arrStatic are \n");
    for(int i: arrStatic) {
      System.out.print(i + " ");
    }
    System.out.println();
    
    int arrDynamic[] = new int[4];
    
    // initialize the array dynamically
    System.out.println("\n Enter values for the array elements");
    for(int i = 0; i < arrDynamic.length; i++) {
        System.out.println("Enter value for arr[" + i + "]:");
        Scanner sc = new Scanner(System.in);
        arrDynamic[i]=sc.nextInt();
    }
    
    System.out.println("elements of the arrDynamic are \n");
    
    // display array elements using for each loop
    for(int i: arrDynamic) {
      System.out.print(i + " ");
    }
  }
}

Output:

1d array

Multiple Dimensional Array:

A multidimensional array stores data in row and column based index like a matrix form.

Declare a 2D array:

data_type[][] arrayName; 
data_type [][]arrayName; 
data_type arrayName[][];

For Example,

int[][] arr; 
int [][]arr; 
int arr[][];

Initialize a 2D array

arrayName = new data_type[size][size];

For Example: arr = new int[5][5];

Instantiate a 2D array

arr[0][0]=10;
arr[0][1]= 20;

Objective: Write a program to initialize and display all the elements of a multidimensional array

import java.util.Scanner;

public class ArrayMultiDisplay {
  public static void main(String[] args) {
    int arr[][] = new int[3][2];
    int i, j;
    
    // initialize the array
    System.out.println("Enter values for the array elements");
    for(i = 0; i < 3; i++) {
       for(j = 0; j < 2; j++) {
          System.out.println("Enter value for arr[" + i + "][" + j + "]:");
          Scanner sc = new Scanner(System.in);
          arr[i][j]=sc.nextInt();
       }
    }
    
    // display array elements using for loop
    System.out.println("elements of the array are \n");
    for(i = 0; i < 3; i++) {
      for(j = 0; j < 2; j++) {
         System.out.print(arr[i][j] + " ");
      }
      System.out.println();
    }
  }
}

Output:

2d array

Jagged Array in Java:

  • This type of array also comes under the multidimensional array.
  • But it has a difference i.e. in a Jagged Array, the number of columns is different in each row.

Syntax to Declare and instantiate a Jagged Array in Java:

data_type arrayName[][] = new data_type[rowSize][];
arrayName[row0][] = new data_type[colSize1];
arrayName[row1][] = new data_type[colSize2];
arrayName[row3][] = new data_type[colSize3];

Objective: Program to show an implementation of a jagged array.

public class JaggedArray {

  public static void main(String[] args) {
    int num[][];
    
    num=new int[6][];
    num[0] = new int[7];
    num[1] = new int[2];
    num[2] = new int[4];
    num[3] = new int[1];
    num[4] = new int[10];
    num[5] = new int[3];
    
    System.out.println("Elements of 2D Jagged Array"); 
        for (int i=0; i<num.length; i++) {
 
            for (int j = 0; j < num[i].length; j++) {
                System.out.print(num[i][j] + " "); 
            }
            System.out.println(); 
        } 
   }
}


Output:

JaggedArray

Java also supports a predefined Array Class in its util package. It contains many predefined methods to manipulate arrays. We will study these in details in the next Java series i.e “Advanced Implementation of Java”.

In the next article of this series, i will give an introduction to strings and String class present in Java. It will also contain how to create strings as well as manipulate them.