Search code examples
javastringarraylistruntime-errorprintln

Runtime error Java


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


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;
    }