Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^488) | One-Dimensional Arrays
Look closely at this example: lettersand upperCaseare composite variables of type char[],
but lowerCaseis a simple variable of type char. If you use the syntax that we introduced first,
you cannot forget to put the brackets on one of the array identifiers:
char[] letters, upperCase, lowerCase;


Declaring and Creating an Array with an Initializer List


Java also provides an alternative way to instantiate an array. You learned previously that
Java allows you to initialize a variable in its declaration:

int delta = 25;

The value 25 is called an initializer. You can also initialize an array in its declaration, using a
special syntax for the initializer. In this case, you specify a list of initial values for the array
elements, separate them with commas, and enclose the list within braces:

int[] age = {23, 10, 16, 37, 12};

In this declaration,age[0]is initialized to 23,age[1]is initialized to 10, and so on. Notice two
interesting things about this syntax. First, it does not use the newoperator. Second, it does not
specify the number of components. When the compiler sees an initializer list, it determines
the size by finding the number of items in the list, instantiates an array of that size, and
stores the values into their proper places. Of course, the types of the values in the initializer
list must match the type of the array.
What values are stored in an array when it is instantiated by using new? If the array com-
ponents are primitive types, they are set to their default value: 0 for integral types,0.0for float-
ing-point types, and falsefor Boolean types. If the array components are reference types, the
components are set to null.
In only two situations can an object be created without using new: when using an array
initializer list and by creating a Stringliteral.

Accessing Individual Components


Recall that to access an individual field of a class, we use dot notation—the name of the
class object, followed by a period, followed by the field name. In contrast, to access an indi-
vidual array component, we write the array name, followed by an expression enclosed in
square brackets. The expression specifies which component to access. The syntax template
for accessing an array component follows:

Array-Component-Access

Array-Name[Index-Expression]
Free download pdf