Which of the following is a legal way to declare and instantiate an array of 10 Strings?
a) String s = new String(10);
b) String[10] s = new String;
c) String[ ] s = new String[10];
d) String s = new String[10];
e) String[ ] s = new String;
9 4 12 2 6 8 18
Answer: c. Explanation: Declaring an array is done by type[ ] variable. Instantiating the array is done by variable =new type[dimension] where dimension is the size of the array.
Assume values is an int array that is currently filled to capacity, with the following values:
a) output 7
b) output 18
c) output nothing
d) cause an ArrayOutOfBoundsException to be thrown
e) cause a syntax error
Answer: d. Explanation: The array has 7 values, but these are indexed values[0] to values[6]. Since values[7] is beyond the bounds of the array, values[7] causes an ArrayOutOfBoundsException to be thrown.
Which of the following loops would adequately add 1 to each element stored in values?
Assume values is an int array that is currently filled to capacity, with the following values:
a) for(j=1;j<values.length;j++) values[j]++;
b) for(j=0;j<values.length;j++) values[j]++;
c) for(j=0;j<=values.length;j++) values[j]++;
d) for(j=0;j<values.length–1;j++) values[j]++;
e) for(j=1;j<values.length–1;j++) values[j]++;
Answer: b. Explanation: The first array element is values[0], so the for-loop must start at 0, not 1. There are values.length elements in the array where the last element is at values.length–1, so the for loop must stop before reaching values.length. This is the case in b. In d, the for loop stops 1 before values.length since “<” is being used to test the condition instead of <=.
Assume values is an int array that is currently filled to capacity, with the following values:
a) 0
b) 5
c) 6
d) 7
e) 18
Answer: d. Explanation: The length operator for an array returns the size of the array. The above picture shows that that values stores 7 elements and since it is full, the size of values is 7.