string - Runtime error Java -


i beginner in java , have run time error question. have answered correctly, not understand concept behind answer. please explain why b right answer question, thank you:

consider 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 list not null, 1 of following true invocations of printall()?

a)a run-time error occurs if list empty.

b)a run-time error occurs if list not empty.

c)a run-time error never occurs.

d)a run-time error occurs.

e)a run-time error occurs whenever list has length

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

here index incremented before accessing list. reads 1 element ahead everytime. run-time error when list not empty.

if list empty condition while (index < list.size) fail , hence loop code causes run-time error never executed.

although not relevant question, correct code increment index after reading:

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

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -