Menu
Topics Index
...
`


Array - Overview >
Siva Nookala - 11 Apr 2016
Array Initializer provides a way to initialize the array elements with values, the moment it is declared. This removes the two step process of declaring and then initializing the values. It also automatically takes care of the length of the array.

With out using the array initializer, we have to do the following if we want to create a marks array for a class with 4 students.
int marks[] = new int[4];
marks[0] = 87;
marks[1] = 76;
marks[2] = 84;
marks[3] = 57;
Using array initializer, we can achieve the same by using
int marks[] = {87, 76, 84, 57};
This type of initialization can be used only along with declaration and will not work, if we assign it to an existing array variable.
int marks[] = new int[4]; // declared separately
marks = {87, 76, 84, 57}; // Not valid, will throw an compilation error.

If we want to assign to an existing array we need to do the following.
int marks[] = null; // declared separately
marks = new int[] {87, 76, 84, 57}; // This will work. Note the new keyword

Array initializer can also be used to initialize multi dimensional arrays. Below is an example marks obtained by 3 students in 4 subjects.
int marks[][] = {
        {25, 24, 12}, // Subject 1
        {42, 67, 81}, // Subject 2
        {29, 63, 94}, // Subject 3
        {31, 98, 43}  // Subject 4
        };
Every subject array contains the marks of the three students. For e.g., 25 is the marks obtained by Student 1 in Subject 1, 98 is the marks obtained by Student 2 in Subject 4.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.