How to initialize an array in Java

Hi coders! In this tutorial, we are going to discuss a very famous data structure known as Array. Today’s topic is how to initialize an array in Java.

Array is a linear data structure which stores a set of same data in a continuous manner.  Array is a very useful data structure since it can store a set of data in a manner so that any operation on the data is easy.

Array is of two types:

  1. One – dimensional array: This can be represented as {1, 2, 3, 5, 6} or ( a, b, g, h, e} etc.
  2. Two – dimensional array: This can be represented as{ {10, 11, 12, 13},{14, 15, 16, 17}}

Now to initialize array there are various ways:

To initialize array in java – primitive data type

int[] arr = new int[5]  (int array declaration of size 5 )

To initialize array in java – object type

String[] strArr = new String[3]

To initialize array in java – using shortcut

int[] arr1 = {1, 2, 3, 4} (one dimentional int array)

int[] arr2 = {{1, 2, 3}, {4, 5, 6}} (two dimensional int array)

To initialize multi-dimensional array 

int[][] arrMulti = new int[4][3]    (2D array declaration)  

Simple example of creating array of one and multiple dimensional in Java

public class ArrayInitialize {
public static void main(String[] args) {
// one dimensional array
int[] arr1 = new int[5];
 // two dimensional array
int[][] arr2 = new int[4][3];
 //object one dimensional array
 String[] strArr = new String[5];
// initialization using shortcut syntax
int[] arr = {1, 2, 3}; //1D array
  int [][] arr = {{1,2,3},{4,5,6}}; // 2D array

There are some invalid ways of array initialization in java

int[] arr = new int[] // size of array must be there

int[] arr = new int[4][5].

Instantiating an array in java

To create an array the actual syntax is like

int[] arr = new int[5], when the new keyword is used then only the memory is allocated to array.

Example

int[] arr //declaring array

arr = new int[10] //  allocating memory

Code to initialize array in Java

class ArrayInitialize  
{ 
    public static void main (String[] args)  
    {          
      // declarint an Array of integers 
      int[] arr = new int[6];
                
      // initialising elements one by one
      arr[0] = 4; 
      arr[1] = 10; 
      arr[2] = 30; 
      arr[3] = 15; 
      arr[4] = 45; 
      arr[5] = 41;
          
     // loop to access elements
      for (int i = 0; i < arr.length; i++) 
         System.out.println(" array element at index " + i +  
                                      " : "+ arr[i]);           
    } 
}
Output:
array element at index 0 : 4
array element at index 1 : 10
array element at index 2 : 30
array element at index 3 : 15
array element at index 4 : 45
array element at index 5 : 41

Java array index is used here.

Also read:

Leave a Reply

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