1
0

## Initializing Array in Java

Java provides the means of declaring, constructing, and explicitly initializing an array in one declaration statement:

<element-type>[] <array-name] = {<array-elements-list>};

This form of initialization applies to members as well as local arrays. Here, <array-element-list> is comma-separated list of zero or more expressions. e.g.

int[] IntArray = {1,6,8,4,12,4,5,7,9,3};

The array IntArray is declared as an array of ints. It is constructed to hold 10 elements, where the first element is initialized to the value of the first expression (1), the second element to the value of the second expression, and so on.

It is very important to note here that the following expression is not valid in the case of initializing an array i.e.

int[] IntArray;
IntArray = {1,6,8,4,12,4,5,7,9,3};

but we can initialize an array like this i.e.

int[] IntArray = new int[10] {1,6,8,4,12,4,5,7,9,3};

These types of arrays are called anonymous arrays.

The following program SumArray initializes an array of integers and puts some value in it. It not only prints each value to standard output but also the sum of all integer values.

Program to find the sum of elements of an array

class SumArray
{
public static void main(String args[])
{
int number[] = {1,2,3,4,5,6,7,8,9,10};
int i;
System.out.println("Given Array is... ");
for(i=0; i<10; i++)
{
System.out.print(number[i] + "\t");
}
int sum = 0;
for(i=0; i<10; i++)
{
sum = sum + number[i];
}
System.out.println("Sum of Given array elements: " + sum);
}
}

The output from this program is:

Given Array is...
1	2	3	4	5	6	7	8	9	10
Sum of Given array elements: 55