1

I was writing a random piece of code and it is bothering me as to why the output is 100000000 in this case:

public class HelloWorld {
    public static void main(String[] args) {
try {
    int[] array = {1};
    System.out.print(array[100000000]);
} catch (Exception e) {
    System.out.print(e.getMessage());
}
    }

}

Why does it print 100000000 and where can I read more about this behavior? Thank you.

2 Answers 2

4

You're trying to access an array element at an index that is greater than (or equal to) the length of the array. This will throw an ArrayIndexOutOfBoundsException exception.

ArrayIndexOutOfBoundsException#getMessage() seemingly returns a String representing the index you tried to access.

Sign up to request clarification or add additional context in comments.

1 Comment

I was expecting it to throw ArrayIndexOutOfBoundsException but I ignored the fact that I was just printing the message in the exception. Thank you this was helpful!
2

Because that is what the message property of the exception java.lang.ArrayIndexOutOfBoundsException thrown is set to. Try adding e.printStackTrace(); in the your catch block and it will print something like :

java.lang.ArrayIndexOutOfBoundsException: 100000000 at com.xxx.SomeTest.main(SomeTest.java:<< line number >>)

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.