0

Can't really understand what's going wrong here?

It's just a simple exception with an array out of bounds.

public class Days
{
    public static void main (String args[])
    {
        String[] dayArray = new String [4];
        {
            dayArray [0] = "monday";
            dayArray [1] = "tuesday";
            dayArray [2] = "wednesday";
            dayArray [3] = "Thursday";
            dayArray [4] = "Friday";

            try
            {
                System.out.println("The day is " + dayArray[5]);
            }
            catch(ArrayIndexOutOfBoundsException Q)
            {
                System.out.println(" invalid");
                Q.getStackTrace();
            }
            System.out.println("End Of Program");
        }
    }
}

Does anybody have any ideas as too why this won't run? I'm getting the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Days.main(Days.java:14)
1
  • 1
    It is straightforward you declare array with 5 element and you use 6'th element that not exist and out of bound Commented Nov 18, 2009 at 13:50

5 Answers 5

7

You should declare it as capable of 5 items, not 4, in its declaration.

new String [5];
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly. For convenience, here's the Arrays Tutorial: java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
and 5th element is dayArray[4]
2

Array are limited on creation. In your example, it has a size of 4 fields.
With a 0-indexed array it means you can access these fields, not any more:

dayArray [0] = "monday";
dayArray [1] = "tuesday";
dayArray [2] = "wednesday";
dayArray [3] = "Thursday";

1 Comment

ah so my array was too small. i wanst aware of that.
2

When appropriate, let the compiler do the counting for you:

String[] dayArray = {
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
};

This way, you can add or remove elements without having to change the array length in another place. Less typing, too.

Comments

0

You array has a size of 4, and you are adding 5 elements.

Comments

0

You're defining five elements for a four element array. Java uses zero based indexes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.