The array elements of an array can be initialized, with values of your choice, at the time the array is being created. To accomplish this, you first need to write the declaration of the array variable as usual. However, instead of creating the array object using the new keyword, as in the following
new int [6];
you can specify the list of initialization values explicitly by enclosing them in braces, and assigning this list to the array variable with the assignment operator. The following line follows this procedure:
The array object is automatically created with just enough array elements (six, in this example) to hold the values specified within the braces. Because the number of values provided inside the braces determines the length of the array, there is no need to specify the length explicitly. Only values implicitly convertible to the base type specified in the declaration (byte in this case) can be included within the braces.
Note
It is possible to specify the length of the array in addition to providing the initialization values enclosed in braces, as in the following line that is equivalent to the previous line. byte [] ages = new byte [6] { 23, 27, 21, 30, 19, 34} ; new int [6] is redundant, but it might, in some cases, be wise to explicitly specify the length in this way; it has two advantages:
|
When you utilize the braces to initialize an array, you must provide an initialization value for all the array elements. If you don't want to assign a value to every single element, you can use one of two procedures:
Supply the initialization values in the braces as before, but let all elements you don't want to assign be set to the default initialization value (in this case, 0), or provide your own "missing value" value. For example, if you did not know the last three initialization values provided earlier (30, 19, and 34), you could write the following:
byte [] ages = { 23, 27, 21, 0, 0, 0} ;
Use the standard assignment operator as in the following:
byte [] ages = new byte [6]; ages[0] = 23; ages[1] = 27; ages[2] = 21; ages[3] = 0; ages[4] = 0; ages[5] = 0;
which again only sets the first, second, and third elements.
Syntax Box 10.3 Declaration and Manual Initialization of an ArrayArray_declaration_with_manual_initialization::= <Base_type> [] <Array_identifier> = [new <Base_type> [<Array_length> ]...] {<Value1>, <Value2>,...<ValueN>} ; Notes:
|