Before your for() loop ends, i
will have a value of len
. Then you set l = i + 1
which is out of bounds and fetch later on inp.charAt(l)
. That's it.
After further investigation (I have not ran the program in my IDE, just read your code) I observed the true cause I guess. Look at inp = z
for each iteration of i
. When i
growth, z becomes shorter and shorter, because it starts with " "
, concats one x
and the rest of len - i
. This will be shorter than your l
, which will be someone in time len + 1
or at least len
. The value of l
is not synchronized with the variation of inp
in each iteration of the i
loop.