Getting a "String index out of range: -1" error

This method is supposed to switch the first letter of the string with the last letter

public static String frontBack(String str)

{

return (str.substring(str.length()-1, str.length()) + str.substring(1, str.length()-1) + str.substring(0, 1));

}

I run the code, and it compiles fine and returns the correct output, but I get an error message saying "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1".

Through some testing, I found that the part of the code causing this issue is str.substring(1, str.length()-1), but I have no idea why. (1, str.length()-1) should be within range.

The argument passed is "code",...

Read More »

By: StackOverFlow - Tuesday, 13 March

Related Posts