Ekaterina1234 Ekaterina1234 - 1 year ago 120
Java Question

java.lang.StringIndexOutOfBoundsException: String index out of range:

I know that simillar questions have been asked, but they all had the same problem: inside of the loop they had something like

i <= aString.lenth()

I used

i < phrase.length();

and I'm still getting the error. I also tried

i < phrase.length()-1;

Any ideas what is wrong?


public class WordPlay {
public boolean isVowel(char c) {
if(c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U') {
return true;
return false;
public void testIsVowel () {
public String replaceVowels (String phrase, char ch){
StringBuilder replaced = new StringBuilder(phrase);
for (int i = 0; i<phrase.length(); i++) {
char currChar = phrase.charAt(i);
if (isVowel(currChar)){

//the line below causes the error
replaced.setCharAt(currChar, ch);
return replaced.toString();
public void testReplaceVowels() {
System.out.println(replaceVowels("Hello World", '*'));


Answer Source

In your call to StringBuilder.setCharAt

replaced.setCharAt(currChar, ch);

the first argument should be i, not currChar:

replaced.setCharAt(i, ch);

You should pass the index you want to set the char at, not the character itself.

currChar's int value is probably higher than the length of your StringBuilder, which caused the exception, but if it wasn't, you would get strange output without an exception, which is even worse.