by Dinesh Thakur Category: array

When an array is created, each element of the array is set to default initial value according to its type. However, it is also possible to provide value other than the default values to each element of the array.

This is made possible using array initialization. Arrays can be initialized by providing values using a comma separated list within curly braces following their declaration. The syntax for array initialization is

datatype[] arrayName = {value1, value2,………………. };

For example : The statement

int[] num = {5,15,25,30,50};

creates a five element array with index values 0,1,2,3,4. The element num [0] is initialized to 5, num [1] is initialized to 15 and so on.

Note that we do not use the new keyword and do not specify the size of the array also. This is because when the compiler encounters such a statement it counts the number of element in the list to determine the size of the array and performs the task performed by the new operator. Initializing array is useful if you know the exact number and values of elements in an array at compile time.

The above initialization statement is equivalent to

int[] num = new int[5];

num [0] =  5 ;

num [1] = 15;

num [2] = 25;

num [3] = 30;

num [4] = 40;

Similarly, you can initialize an array by providing objects in the list. For example

Rectangle[] rect = {new Rectangle(2,3),new Rectangle()};

It will create rect array of Rectangle objects containing 2 elements.

There is a variation of array initialization in which we use the new keyword explicitly but omit the array length as it is determined from the initializer list. For example:

int[] num = new int[]{5,15,25,30,50};

This form of initialization is useful if you need to declare an array in one location but populate it in another while still taking the advantage of array initialization. For example:

displayData(new String[]{"apple","orange","litchi"});

An unnamed array created in such a way is called anonymous arrays.

public class InitializingArray

          public static void main(String[] args)
           int[] num = new int[]{5,15,25,30,500};
           for(int i=0;i<num.length;i++)
                 System.out.println("num ["+i+"] : " +num[i]);
          display(new String[] {"apple","orange","1itchi"});
          static void display(String[] str)
          for(int i=0;i<str.length;i++)
                  System.out.println("str ["+i+"] :" +str[i]);

Initializing Array in Java

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles