foreach causing out of bounds error in Java when used with array -
this question has answer here:
- enhanced loop exception [duplicate] 3 answers
i want print elements in array using foreach loop
int[] array={1,2,3,4,5}; for(int i:array) system.out.println(array[i]);
and compilers gives me error/warning
exception in thread "main" java.lang.arrayindexoutofboundsexception: 5
but when print else
int[] array={1,2,3,4,5}; for(int i:array) system.out.println("print something");
it writes "print something" 5 times , gives no warning/error.
i assume has first element in array has index 0, not sure.
can explain why ?
in first chunk of code, not printing elements in array. going through elements in array , each element printing entry in array corresponding element's value.
what want this:
int[] array={1,2,3,4,5}; for(int i:array) system.out.println(i);
Comments
Post a Comment