Java Reference
In-Depth Information
f)
Sum all the elements of the array, using a
for
statement. Declare the integer variable
x
as a control variable for the loop.
7.4
Perform the following tasks for an array called
table
:
a)
Declare and create the array as an integer array that has three rows and three columns.
Assume that the constant
ARRAY_SIZE
has been declared to be
3
.
b)
How many elements does the array contain?
c)
Use a
for
statement to initialize each element of the array to the sum of its indices. As-
sume that the integer variables
x
and
y
are declared as control variables.
7.5
Find and correct the error in each of the following program segments:
a)
final int
ARRAY_SIZE
=
5
;
ARRAY_SIZE
=
10
;
b)
Assume
int
[] b =
new
int
[
10
];
for
(
int
i =
0
; i <= b.length; i++)
b[i] =
1
;
c)
Assume
int
[][] a = {{
1
,
2
}, {
3
,
4
}};
a[
1
,
1
] =
5
;
Answers to Self-Review Exercises
7.1
a) arrays, collections. b) variables, type. c) enhanced
for
statement. d) index (or subscript
or position number). e) two-dimensional. f)
for
(double
d
:
numbers
). g) an array of
String
s, called
args
by convention. h)
args.length
. i)
test
. j) ellipsis (
...
).
7.2
a)
False. An array can store only values of the same type.
b)
False. An array index must be an integer or an integer expression.
c)
For individual primitive-type elements of an array: False. A called method receives and
manipulates a copy of the value of such an element, so modifications do not affect the
original value. If the reference of an array is passed to a method, however, modifications
to the array elements made in the called method are indeed reflected in the original. For
individual elements of a reference type: True. A called method receives a copy of the
reference of such an element, and changes to the referenced object will be reflected in
the original array element.
d)
False. Command-line arguments are separated by white space.
7.3
a)
final int
ARRAY_SIZE
=
10
;
b)
double
[] fractions =
new
double
[
ARRAY_SIZE
];
c)
fractions[
4
]
d)
fractions[
9
] =
1.667
;
e)
fractions[
6
] =
3.333
;
f)
double
total =
0.0
;
for
(
int
x =
0
; x < fractions.length; x++)
total += fractions[x];
7.4
a)
int
[][] table =
new
int
[
ARRAY_SIZE
][
ARRAY_SIZE
];
b) Nine.
c)
for
(
int
x =
0
; x < table.length; x++)
for
(
int
y =
0
; y < table[x].length; y++)
table[x][y] = x + y;
7.5
a)
Error: Assigning a value to a constant after it has been initialized.
Correction: Assign the correct value to the constant in a
final
int
ARRAY_SIZE
declaration or declare another variable.