Reputation:
I just read the intro to arrays section in my AP Java book and tried the following example however I get an error and cant understand why.
Code:
public static void arrayT(int i){
String[] alphabet = new String[5];
alphabet[0] = "a";
alphabet[1] = "c";
alphabet[2] = "x";
alphabet[3] = "b";
alphabet[4] = "d";
alphabet[5] = "e";
System.out.println(alphabet[i]);
}
Main:
public static void main(String [] args){
arrayT(2);
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.arrayT(Main.java:18)
at Main.main(Main.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
What am I doing wrong?
Upvotes: 0
Views: 78
Reputation: 1941
public static void arrayT(int i){
String[] alphabet = new String[5];
alphabet[0] = "a";
alphabet[1] = "c";
alphabet[2] = "x";
alphabet[3] = "b";
alphabet[4] = "d";
alphabet[5] = "e";
System.out.println(alphabet[i]);
}
in this when you declared statement
String[] alphabet = new String[5];
then ur String Array size is 5 i.e 0-4(including 0 then total is 5 elements can be added)
so u have to increase the size of String array to 6 so as to add 6 elements
String[] alphabet = new String[6];
Upvotes: 0
Reputation: 3197
This is because you declare the array with length 5 but you assign 6 values to it.
alphabet[5] = "e";. This one causes 'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5'
Try to set the length of array with length 6. Then you will get the right result.
String[] alphabet = new String[6];
Upvotes: 0
Reputation: 8337
Array defined is of length 5, and with alphabet[5] = "e";
you are trying to add 6'th element to array. Either define array with legnth as 6
String[] alphabet = new String[6];
Or remove last line of code
alphabet[5] = "e"
Upvotes: 0
Reputation: 12527
String[] alphabet = new String[5];
The above statement allocates an array with a capacity of 5. Valid indecies are 0, 1, 2, 3, and 4.
Index 5 is out of bounds. Thus:
alphabet[5] = "e";
throws the exception.
Upvotes: 4
Reputation: 17871
String[] alphabet = new String[5];
creates an array of length 5, that is it has indexes 0, 1, 2, 3, 4 and exactly five elements in it. You are trying to access an element which isn't there, under index 5.
Upvotes: 1