Search code examples
javastringpalindrome

Can somebody spot the error in this java program


My program should check whether the input is a palindrome or not. The given program compiles and runs successfully. Program prints reverse string correctly but gives wrong output. Please help!

class Palindrome
{
    public static void main(String[] args)
    {   
        String str,revStr="";
        System.out.println("Enter something to check if it is a palindrome");
        Scanner sn = new Scanner(System.in);
        str = sn.nextLine();
        for(int i=str.length()-1;i>=0;i--)
        {
            revStr+=Character.toString(str.charAt(i));
        }
        if(revStr==str)
        {
         System.out.println("The string "+str+" is a Palindrome");
         System.out.println(revStr);
        }
        else
        {
            System.out.println("The string "+str+" is not a Palindrome");
            System.out.println(revStr);
        }
    }
}

output:

Enter something to check if it is a palindrome
nitin
The string nitin is not a Palindrome
nitin

Solution

  • Here change this line if(revStr==str) To If ( revStr.equals(str))

    The thing is == checks reference equality

    Object.equals is the method given in java to define your object equality String class overrides that and check if two Strings represent same char array