Question

I am a beginner in Java and I have a run time error question. I have answered it correctly, however I do not completely understand the concept behind the answer. Could someone please explain why B is the right answer to the question, thank you:

Consider the following declarations:

private ArrayList<String> list;
...
public void printAll()
{
int index = 0;
while (index < list.size) {
index = index + 1;
System.out.println(list.get(index));
   }
}

Assuming that list is not null, which one of the following is true about invocations of printAll()?

a)A run-time error occurs only if the list is empty.

b)A run-time error occurs only if the list is not empty.

c)A run-time error never occurs.

d)A run-time error always occurs.

e)A run-time error occurs whenever the list has an even length

Was it helpful?

Solution

while (index < list.size) {
 index = index + 1;
 System.out.println(list.get(index));
}

Here index is incremented before accessing the list. So it reads one element ahead everytime. So run-time error when the list is not empty.

If the list is empty then the condition while (index < list.size) will fail and hence the loop code that causes the run-time error will never be executed.

Although not relevant to your question, the correct code would be to increment the index after reading:

while (index < list.size) {
 System.out.println(list.get(index));
 index = index + 1;
}

OTHER TIPS

consider list have 10 items, then indexes were 0 - 9

now when index=9

while loop check it 9<10 which is true and enters in then add 1

index become 10 which is out of bound error occured

while (index < list.size) {
 index = index + 1;
 System.out.println(list.get(index));
}

case 1

: if list is empty, content of while loop will never be executed.

case 2

:if list is not empty, accessing last element will occurs an error. Because the element at list.size is not there in list.

So, that error occurs only if list contains at least one element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top