29.4k views
0 votes
Consider the following method:

public static void doStuff (int a[], int b) {
if (/* Missing Code */) {
for (int i = b; i < a.length; i++) {
a[i] = a[i] * 2;
}
}
}

What could be used to replace / *Missing Code* / so that there is no out of bounds exception?

a. b < a.length
b. b > 0 b < a.length
c. b > 0 && b <= a.length
d. b >= 0 || b < a.length
e. b >= 0 && b < a.length

User Szymond
by
5.9k points

1 Answer

2 votes

Answer:

e. b >= 0 && b < a.length

Step-by-step explanation:

Array indices in java begin at 0 and go up to number n-1, where n is the length of the array.

Note: a.length returns the length of the array. We can assume the array length to be n for this case.

Option a is incorrect since b can be less than 0, which causes an out of bounds exception.

Option b is incorrect because two comparison statements are separated by a boolean operator, therefore it will cause a syntax error.

Option c is incorrect because if b = a.length, this means that i will begin from nth index of the array, where as array indices only range from 0 to n-1 as mentioned earlier.

Option d is incorrect because it uses the || (or) operator. This means that only one condition of the two given has to be true. Suppose if b is negative, this will cause b >= 0 to be false. However, since array length can never be negative, b < a.length will always be True, hence we can have an out of bounds exception in this case.

User Fabio Cenni
by
5.5k points