-3

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 6 out of bounds for length 6

Process finished with exit code 1


    public class Main {
        boolean palindrome(String str, int start, int end){
            if(start >= end)
                return true;
            return(str.charAt(start) == str.charAt(end)) && palindrome(str, start+1, end-1);
    }
        public static void main(String[] args) {
            String str = "aabbaa";
            int n = str.length();
            System.out.println(palindrome(str, 0, n));
        }
    }

Raj
  • 63
  • 1
  • 8
  • 1
    What is your question? What shall we comment here? – MWiesner Aug 09 '22 at 14:47
  • 1
    [What is a StringIndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/q/40006317/12567365) – andrewJames Aug 09 '22 at 14:51
  • 1
    You are getting a string index out of bounds exception because you are indexing into a string and that index is out of bounds. I don't know how else you want that phrased. The error message literally gives you a line number *and* the index and length of the string. – Silvio Mayolo Aug 09 '22 at 14:52

2 Answers2

0

String's length() function returns the "real" length of the string, so if you used six letters, it would return 6. However, in programming we start indexing at 0, that means the 6th letter of the word would be indexed as 5.

When you call your palindrome() method with the value of 6 as the end parameter, you are telling the code to find the letter with the index of 6, which your string does not have, as the last letter would be indexed as 5 in your case.

You should use line.length() - 1 when using indexes.

Read more: java.lang.StringIndexOutOfBoundsException?

nnntm
  • 27
  • 5
0

You should use int n = str.length() - 1; which is how you get the last index.

if str.length() is 6, the indexes are 0-5 not 1-6.

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94