In the loop you want to use i, but dealing with m. Even you are decreasing m. Whenever m is decreased to 0, s.charAt(m-1) is trying to find character in negative position of the string. As a result, you are getting StringIndexOutOfBoundsException. So, instead of