Your while
loop is perfetly fine, but after it ends, the value of i
is 5
. Since java arrays are always indexed from zero, list[5]
doesn't exist and accessing it throws exception.
That's what you see when printing System.out.print(list[i] + " ");
Just print any other element, list[1]
, list[4]
or list[0]
for example.