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.
Using array initializer, we can achieve the same by using
This type of initialization can be used only along with declaration and will not work, if we assign it to an existing array variable.
If we want to assign to an existing array we need to do the following.
Array initializer can also be used to initialize multi dimensional arrays. Below is an example marks obtained by 3 students in 4 subjects.
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.