Java-Array Declaration and Initialization

Array Declaration and Initialization Methods

Arrays can be assigned initial values in the declaration statement itself. An ‘array initializer’ is a list of comma-separated expressions surrounded by curly braces. The commas separate the values of the array elements. The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new. For example :


The second statement can equivalently to the first statement .

The first statement declares that array_v3 is an array integers. The second statement array_v3 = new int[5] initializes the integer array array_v3 with five entities. The above two statements can equivalently be written as follows:

This can also be written in a single statement as


Program Source

public class Javaapp {
    public static void main(String[] args) {
        int[] array_v1 = new int[5];
        array_v1[0] = 20;
        array_v1[1] = 40;
        array_v1[2] = 60;
        array_v1[3] = 80;
        array_v1[4] = 100;
        int[] array_v2 = {10,30,50,70,90};
        int[] array_v3 = new int[]{5,10,15,20,25};
        int[] array_v4;
        array_v4 = new int[5];
        array_v4[0] = 2;
        array_v4[1] = 4;
        array_v4[2] = 6;
        array_v4[3] = 8;
        array_v4[4] = 100;