Piece

Array [C# Java] 1 Dimensional Array Initialization

More Code 2018. 6. 24. 20:55

[C# Java] 1차원 배열의 초기화 방법에 대해서 알아보자.



// [C# Java] OK. Since arrays are objects, we need to instantiate them with the new keyword
int[] myArray = new int[3];
myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;



// [C#] OK. We can provide initial values to the array when it is declared by using curly brackets
// [Java] Error. We can not define dimension expressions when an array initializer is provided
int[] myArray = new int[3] { 10, 20, 30 }; // [C#] OK. [Java] Error



// [C# Java] OK. We can omit the size declaration when the number of elements are provided in the curly braces
int[] myArray = new int[] { 10, 20, 30 };



// [C# Java] OK. We can even omit the new operator. The following statements are identical to the ones above
int[] myArray = { 10, 20, 30 };



// It is possible to declare an array variable without initialization.
// But you must use the new operator when you assign an array to this variable.

int[] myArray;
myArray = new int[3]; // [C# Java] OK

int[] myArray;
myArray = new int[3] { 10, 20, 30 }; // [C#] OK. [Java] Error

int[] myArray;
myArray = new int[] { 10, 20, 30 }; // [C# Java] OK

int[] myArray;
myArray = { 10, 20, 30 }; // [C# Java] Error. You must use the new operator