Java Reference
In-Depth Information
a primitive data type in its declaration except that an array requires
several values.
The items in an initializer list are separated by commas and delim-
ited by braces ( {} ). When an initializer list is used, the new operator
is not used. The size of the array is determined by the number of
items in the initializer list. For example, the following declaration
instantiates the array scores as an array of eight integers, indexed from 0 to 7
with the specified initial values:
KEY CONCEPT
An initializer list can be used to
instantiate an array object instead of
using the new operator.
int [] scores = {87, 98, 69, 87, 65, 76, 99, 83};
An initializer list can be used only when an array is first declared.
The type of each value in an initializer list must match the type of the array
elements. Let's look at another example:
char [] vowels = {'A', 'E', 'I', 'O', 'U'};
In this case, the variable vowels is declared to be an array of five characters, and
the initializer list contains character literals.
The program shown in Listing 8.4 demonstrates the use of an initializer list to
instantiate an array.
Arrays as Parameters
An entire array can be passed as a parameter to a method. Because
an array is an object, when an entire array is passed as a parameter,
a copy of the reference to the original array is passed. We discussed
this issue as it applies to all objects in Chapter 7.
A method that receives an array as a parameter can permanently
change an element of the array, because it is referring to the original
element value. The method cannot permanently change the reference to the array
itself, because a copy of the original reference is sent to the method. These rules
are consistent with the rules that govern any object type.
An element of an array can be passed to a method as well. If the element type is
a primitive type, a copy of the value is passed. If that element is a reference to an
object, a copy of the object reference is passed. As always, the impact of changes
made to a parameter inside the method depends on the type of the parameter. We
discuss arrays of objects further in the next section.
KEY CONCEPT
An entire array can be passed as
a parameter, making the formal
parameter an alias of the original.
 
Search WWH ::




Custom Search