javaarraysstringpalindrome

Logical Error in program while finding if string is Palindrome


This program to find if a string is a palindrome is not working properly due to logical errors. Pls help me correct this program.

public class Palindrome {
        public String checkPal(String strr){
            String rev;
            char[] C = strr.toCharArray();
            int left=0;
            int right= (C.length)-1;
            while(left<right){
                char t=C[left];
                C[left++] = C[right];
                C[right--] = t;
            }
            for(int i=0; i<(C.length); i++){
                
            }
            rev = C.toString();
            return rev;
        }
        public static void main(String[] args) {
            String S = "level";
            Palindrome p = new Palindrome();
            String R = p.checkPal(S);
            System.out.println(R);
            if(S.toLowerCase().equals(R.toLowerCase())){
                System.out.println("hey Pal :)");
            }
            else{
                System.out.println("Bye Pal :<");
            }
        }

I tried to find if a string is palindrome and I'm expecting it to display "Hey pal :)" if it is.


Solution

  • C.toString() simply returns the default toString for an array, and does not return your new String

    Try doing

     return new String(C); 
    

    BTW, there is no reason to swap characters. Just copy from right to left. If it is a palindrome, it will be preserved and will compare to the original. Otherwise it won't.

     C[left++] = C[right--]; 
    

    And you can remove your empty for loop as it serves no purpose.