priyanka srivastava priyanka srivastava - 2 months ago 11
Java Question

Palindrome String Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

While trying to check Palindrome String getting this error"String Index out of bound -1"

public static void main(String[]args) {

String s= "Madam";
String Temp=s;
String k=new String();
//System.out.println(s.length());
int m=s.length();

for (int i=5;i>=m;m--) {
System.out.println(m);
String t=String.valueOf(s.charAt(m-1) ) ;
k=k+t;
System.out.println(k);
}

System.out.println(k);

if (k==Temp) {
System.out.println("String is Palindrome"+" "+k);
} else {
System.out.println("String is not Palindrome");
}
}

Answer

In the loop you want to use i, but dealing with m. Even you are decreasing m. Whenever m is decreased to 0, s.charAt(m-1) is trying to find character in negative position of the string. As a result, you are getting StringIndexOutOfBoundsException. So, instead of

for (int i=5;i>=m;m--) {
    System.out.println(m);
    String t=String.valueOf(s.charAt(m-1) ) ;
    k=k+t;
    System.out.println(k);
}

It should be:

for (int i = m-1; i >= 0; i--) {
    String t = String.valueOf(s.charAt(i)) ;
    k=k+t;
    System.out.println(k);
}

Simply the code could be:

String s = "Madam", reverse = "";
int m = s.length();

for (int i = m - 1; i >= 0; i--) {
    reverse += s.charAt(i);
}
System.out.println(reverse);

if (reverse.equalsIgnoreCase(s)) { // don't use '==' for checking equality of strings
    System.out.println(s + " is Palindrome");
} else {
    System.out.println(s + " is not Palindrome");
}