Java Reference
In-Depth Information
1.9. Arrays
Simple variables that hold one value are useful but are not sufficient for
many applications. A program that plays a game of cards would want a
number of
Card
objects it could manipulate as a whole. To meet this need,
you use
arrays.
An array is a collection of variables all of the same type. The components
of an array are accessed by simple integer indexes. In a card game, a
Deck
object might look like this:
public class Deck {
public static final int DECK_SIZE = 52;
private Card[] cards = new Card[DECK_SIZE];
public void print() {
for (int i = 0; i < cards.length; i++)
System.out.println(cards[i]);
}
// ...
}
First we declare a constant called
DECK_SIZE
to define the number of cards
in a deck. This constant is
public
so that anyone can find out how many
cards are in a deck. Next we declare a
cards
field for referring to all the
cards. This field is declared
private
, which means that only the methods
in the current class can access itthis prevents anyone from manipulating
our cards directly. The modifiers
public
and
private
are
access modifiers
because they control who can access a class, interface, field, or method.
We declare the
cards
field as an array of type
Card
by following the type
name in the declaration with square brackets
[
and
]
. We initialize
cards
to a new array with
DECK_SIZE
variables of type
Card
. Each
Card
element in
the array is implicitly initialized to
null
. An array's length is fixed when it
is created and can never change.