Search code examples
javastringassert

ArrayIndexOutOfBoundsException after assert statement


I have a String array tmp got by String[] tmp = line.split(",");

Then,

I got java.lang.ArrayIndexOutOfBoundsException: 3 on code

assert tmp.length == 4;
int r = Integer.parseInt(tmp[3]);   ----error line

and java.lang.ArrayIndexOutOfBoundsException: 2 on code

assert tmp.length == 3;
String name = tmp[2];    -----error line

I do not think this error is reasonable. The assert statement passes correctly and how can a array with .length=4 having no element indexed 3? Could anyone tell me why...


Solution

  • As stated in the comments, the problem here is that you did not activate the assertions in the JVM options

    In command line java MyProgram -ea

    For Eclipse, see this answer.

    For IntelliJ, see this answer.