Java Reference
In-Depth Information
The program defines an array
suits
for four suits (line 4) and an array
ranks
for 13 cards in
a suit (lines 5-6). Each element in these arrays is a string.
The program initializes
deck
with values
0
to
51
in lines 9-10. The
deck
value
0
repre-
sents the card Ace of Spades,
1
represents the card 2 of Spades,
13
represents the card Ace of
Hearts, and
14
represents the card 2 of Hearts.
Lines 13-19 randomly shuffle the deck. After a deck is shuffled,
deck[i]
contains an
arbitrary value.
deck[i] / 13
is
0
,
1
,
2
, or
3
, which determines the suit (line 23).
deck[i]
% 13
is a value between
0
and
12
, which determines the rank (line 24). If the
suits
array is
not defined, you would have to determine the suit using a lengthy multi-way
if-else
state-
ment as follows:
if
(deck[i] /
13
==
0
)
System.out.print(
"suit is Spades"
);
else if
(deck[i] /
13
==
1
)
System.out.print(
"suit is Hearts"
);
else if
(deck[i] /
13
==
2
)
System.out.print(
"suit is Diamonds"
);
els
System.out.print(
"suit is Clubs"
);
With
suits = {"Spades", "Hearts", "Diamonds", "Clubs"}
created in an array,
suits[deck / 13]
gives the suit for the
deck
. Using arrays greatly simplifies the solution
for this program.
To copy the contents of one array into another, you have to copy the array's individual
elements into the other array.
Key
Point
Often, in a program, you need to duplicate an array or a part of an array. In such cases you
could attempt to use the assignment statement (
=
), as follows:
list2 = list1;
However, this statement does not copy the contents of the array referenced by
list1
to
list2
,
but instead merely copies the reference value from
list1
to
list2
. After this statement,
list1
and
list2
reference the same array, as shown in Figure 6.5. The array previously ref-
erenced by
list2
is no longer referenced; it becomes garbage, which will be automatically
collected by the Java Virtual Machine (this process is called
garbage collection
).
copy reference
garbage collection
Before
the assignment
list2 = list1;
After
the assignment
list2 = list1;
list1
list1
Contents
of
list1
Contents
of
list1
list2
list2
Contents
of
list2
Contents
of
list2
F
IGURE
6.5
Before the assignment statement,
list1
and
list2
point to separate memory
locations. After the assignment, the reference of the
list1
array is passed to
list2
.
In Java, you can use assignment statements to copy primitive data type variables, but not
arrays. Assigning one array variable to another array variable actually copies one reference to
another and makes both variables point to the same memory location.