Java Reference
In-Depth Information
Self-Test Exercises
(continued)
2. In the array:
double
[] score =
new double
[10];
what is
a. the value of
score.length
?
b. the first index of
score
?
c. the last index of
score
?
3. What is the output of the following code?
char
[] letter = {'a', 'b', 'c'};
for
(
int
index = 0; index < letter.length; index++)
System.out.print(letter[index] + ", ");
4. What is the output of the following code?
double
[] a = {1.1, 2.2, 3.3};
System.out.println(a[0] + " " + a[1] + " " + a[2]);
a[1] = a[2];
System.out.println(a[0] + " " + a[1] + " " + a[2]);
5. What is wrong with the following piece of code?
int
[] sampleArray =
new int
[10];
for
(
int
index = 1; index <= sampleArray.length; index++)
sampleArray[index] = 3*index;
6. Suppose we expect the elements of the array
a
to be ordered so that
a[0]
≤
a[1]
≤
a[2]
≤...
However, to be safe we want our program to test the array and issue a warning in
case it turns out that some elements are out of order. The following code is
supposed to output such a warning, but it contains a bug; what is the bug?
double
[] a =
new double
[10];
<
Some code to fill the array a goes here.
>
for
(
int
index = 0; index < a.length; index++)
if
(a[index] > a[index + 1])
System.out.println("Array elements " + index +
" and " + (index + 1) + " are out of order.");