How to Declare and Initialize an Array in Java


Here let’s see how to declare and initialize an array in Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class ArrayExample {

    public static void main(String[] args){
    	//declare an array of String
        String[] arr1 = new String[2];
		// index starts with 0
        arr1[0] = "a";
        arr1[1] = "b";
        
        int[] arr2 = {1, 2};
        
        int[] arr3 = new int[]{1, 2};

		// print the arrays
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
        System.out.println(Arrays.toString(arr3));
    }
}

Output:

[a, b]
[1, 2]
[1, 2]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments