-1

I wrote a Java program below:

int[] tar = {1,2,5};
for(int i=0 ; i<tar.length ; i++)
{
   if(tar[i] - tar[i-1] > 2)
   {
      System.out.print("true");
   }
}

why "tar[i] - tar[i-1]" doesn't mean any error? Isn't an error of ArrayIndexOutBoundsException?

David
  • 103
  • 1
  • 6
  • Do you get any output? – Fildor Mar 30 '17 at 07:10
  • Please explain "doesn't mean any error". You mean compile error? – Costi Ciudatu Mar 30 '17 at 07:10
  • 1
    Do you expect a compile error? The error is only going to appear when you run the program. – RealSkeptic Mar 30 '17 at 07:10
  • @GhostCat are you sure about that dupe? This question is "why doesn't this program produce the expected error". – RealSkeptic Mar 30 '17 at 07:12
  • http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/ – amudhan3093 Mar 30 '17 at 07:13
  • @RealSkeptic The questioner gets that exception. He doesn't understand it; as he probably doesn't understand the difference between compile and runtime errors. But there are plenty of explanations on that question ...but you are right, I will put up a comment ... – GhostCat Mar 30 '17 at 07:15
  • 1
    The point is: the compiler doesn't understand that `i-1` results in an **invalid** index (although it would be possible to understand that in certain situations). Thus there is no checking at **compile** time. But an error at runtime ... the one you put in your question title. That is all there is to this. – GhostCat Mar 30 '17 at 07:16

1 Answers1

0

It is an Exception and not error (if you mean it by compiler), cause Java knows about your array values only at run time.

Compiler cannot run your code and see that. What if at runtime you provided some good values at right indices ? That is the reason, compiler only checks the compiler level rules. It won't hint you about runtime behaviour.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307