Search code examples
javaarraysindexoutofboundsexceptionpalindrome

Array index out of bound exception for palindrome java program


Why am i getting the array bound of exception? im beginner in programming. Please help me understand. I have tried to convert the string to char array and reverse the characters and convert the end result back to string and compare with the original string

/* to check if the entered string is palinrome or not*/
class Palin
{
public static void main(String[] args)
{
String name="anna";
int l=name.length();
int d=l/2;
char tmp;
char tmp1;
char[] arr = name.toCharArray();

for(int j=0;j<d;j++)  /*to swap the characters*/
{
tmp=arr[j];
tmp1=arr[l];
arr[j]=tmp1;
arr[l]=tmp;
l=l-1;
}

String str=String.valueOf(arr); /* to convert the swapped char array back to string*/
if (str==name)
System.out.println("True");
else
System.out.println("False");

}
}

Solution

  • An array of N entries can be accessed with an index between 0 and N-1.

    Change this:

    tmp1 = arr[l];
    

    To this:

    tmp1 = arr[l-j-1];
    

    And get rid of this:

    l = l-1;
    

    By the way, swapping can be done in 3 assignment operations instead of 4.

    So you might as well change this:

    tmp = arr[j];
    tmp1 = arr[l];
    arr[j] = tmp1;
    arr[l] = tmp;
    l = l-1;
    

    To this:

    tmp = arr[j];
    arr[j] = arr[l-j-1];
    arr[l-j-1] = tmp;