String index out of bounds exception java

You are calling str.substring(i, j-i) which means substring(beginIndex, endIndex), not substring(beginIndex, lengthOfNewString).

One of assumption of this method is that endIndex is greater or equal beginIndex, if not length of new index will be negative and its value will be thrown in StringIndexOutOfBoundsException.

Maybe you should change your method do something like str.substring(i, j)?


Also if size is length of your str then

for (int i = 0; i <= size; i++)

should probably be

for (int i = 0; i < size; i++)

Leave a Comment