Shreyash Chaudhari
Shreyash Chaudhari

Reputation: 3

Bubble Sort ArrayIndexOutOfBounds in Java

for(i=0;i<=4;i++)
            {
                for(j=0;j<=4;j++)
                {
                    if(hand[j] > hand[j+1])
                    {
                        temp = hand[j];
                        hand[j] = hand[j+1];
                        hand[j+1] = temp;
                    }
                }
            }

When I try to run this bubble sorting program, there's an ArrayIndexOutOfBounds Exception. Why? And how do I fix it?

Upvotes: 0

Views: 80

Answers (3)

Shahar
Shahar

Reputation: 1677

As everyone else said, when you have 5 elements in the array you can only access indices 0 to 4. As far as fixing goes, it should be:

for(i=0;i<4;i++)
{
    for(j=0;j<4-i;j++)
    {
        if(hand[j] > hand[j+1])
        {
            temp = hand[j];
            hand[j] = hand[j+1];
            hand[j+1] = temp;
        }
    }
}

Upvotes: 1

Orel Eraki
Orel Eraki

Reputation: 12196

This happens due the fact your array size is 5 thus the range is from 0-4 while you try to get in the last iteration the value from hand[j+1] that means hand[5] which produces this exception.

Upvotes: 1

Hari Menon
Hari Menon

Reputation: 35405

You are accessing hand[] from index 0 to 5 (since it is j+1). Size of hand[] must be at least 6 for you to be able to do it. In your case, it is not, hence the error.

Upvotes: 1

Related Questions