0

I want to print all 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 this error/warning

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

but when I print something else

int[] array={1,2,3,4,5};
   for(int i:array)
       System.out.println("Print something");

It writes "Print something" five times and gives no warning/error.

I assume it has to do something that first element in array has index 0, but I am not sure.

Can someone explain why ?

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
gilley
  • 49
  • 3
  • 5

2 Answers2

2

You're iterating the contents of the array which is assigned to i, so the code translates to

System.out.println(array[1]);
System.out.println(array[2]);
System.out.println(array[3]);
System.out.println(array[4]);
System.out.println(array[5]);   // ArrayIndexOutOfBoundsException
Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

In your first chunk of code, you are not printing all elements in the array. You are going through all elements in the array and for each element you are printing the entry in the array corresponding to that element's value.

What you want is this:

int[] array={1,2,3,4,5};
   for(int i:array)
       System.out.println(i);
A_K
  • 457
  • 3
  • 11