If “boo” is located at the end of the word, word.substring(word.indexOf("b"),word.indexOf("b")+4)
will give you StringIndexOutOfBoundsException
, since word.indexOf("b")+2
is the last index of the String, and substring
tries to return the characters whose indices are from word.indexOf("b")
to word.indexOf("b")+3
.
You must check that word.indexOf("b")+4 <= word.length()
.