1

I get an exception in my second print line.

int num[] = {50,20,45,82,25,63};
System.out.print("Given number : ");
for(int d:num){
System.out.print("  " + num[d]);
}

The console output is

Given number : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50

Why doesn't d take all the array elements but only 50?

kommradHomer
  • 4,127
  • 5
  • 51
  • 68
Some Java Guy
  • 4,992
  • 19
  • 71
  • 108
  • When you use the foreach syntax: for(int d : num){ // etc } d isn't a index it's the value already indexed!! – MrJames Apr 02 '12 at 11:07

5 Answers5

6

In the for(int d:num) loop every item is represented by d not num[d]

So, here is how it should be done.

for(int d:num){
    System.out.print("  " + d);
}

A simple dry run will show you where you went wrong.

For the first loop your statement will come down to num[50] which is not available anywhere, so you get the exception.


However, if your attempt was to use indexing, then a simple trick below will do the trick

int index = 0;
for(int d:num){
    System.out.print("  " + num[index++]);
}

But I honestly believe, this is not the correct solution to the problem.

Starx
  • 77,474
  • 47
  • 185
  • 261
3

In for each loop num[any index] is not required. It just retrieves from first index to last index and assign each of them to he variable d. So you just need to print the value d.

for(int d:num){
System.out.print("  " + d);
}
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
1

Using the enhanced for loop you can use the varable "d" in your example directly:

System.out.print(d);

The reason you get an ArrayIndexOutOfBound is that num[d] tries to acces the 50th place in the array on first iteration. (Which is out of bound).

Boosty
  • 701
  • 1
  • 5
  • 12
0

You are not suppose to use array index while using for each loop.

In your code,

int num[] = {50,20,45,82,25,63};
System.out.print("Given number : ");
for(int d:num)
{
    System.out.print("  " + num[d]);
}

in the first iteration will result in d = 50, which is your desired result. If you use num[d], it will result in num[50], which is the wrong index.

Instead, use the below code

for(int d:num)
{
    System.out.print("  " + d);
}
Sunil Kumar B M
  • 2,735
  • 1
  • 24
  • 31
0

you might want to code like below.

for(int d:num){
System.out.print("  " + d);
}

How does the Java 'for each' loop work?

Community
  • 1
  • 1
Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40