Indexes begin at 0, so the last character in a String is at position length() - 1. In the code you posted


for (i = 1; i <= str.length(); i++)

the <= will eventually try to access the...