Because
S
is guaranteed to be shorter than
mid
characters long:
String S= A.substring(0,mid-1);
If
mid
is 3, S is two characters, so when your loop generates indexes 0, 1, and 2 the final one is out of bounds.
To be honest, one single minute with the debugger would have shown you that 1/4 hour ago ... I strongly suggest you learn how to use it, it'll save you a huge amount of time in the future.