arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -


what arrayindexoutofboundsexception mean , how rid of it?

here code sample triggers exception:

string[] name = {"tom", "dick", "harry"}; for(int = 0; i<=name.length; i++) {   system.out.print(name[i] +'\n'); } 

your first port of call should documentation explains reasonably clearly:

thrown indicate array has been accessed illegal index. index either negative or greater or equal size of array.

so example:

int[] array = new int[5]; int boom = array[10]; // throws exception 

as how avoid it... um, don't that. careful array indexes.

one problem people run thinking arrays 1-indexed, e.g.

int[] array = new int[5]; // ... populate array here ... (int index = 1; index <= array.length; index++) {     system.out.println(array[index]); } 

that miss out first element (index 0) , throw exception when index 5. valid indexes here 0-4 inclusive. correct, idiomatic for statement here be:

for (int index = 0; index < array.length; index++) 

(that's assuming need index, of course. if can use enhanced loop instead, so.)


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -