-1

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
msrd0
  • 7,816
  • 9
  • 47
  • 82
Abhishek Prakash
  • 151
  • 1
  • 1
  • 12

3 Answers3

0

Your answer here:

import java.util.Scanner;

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));
            System.out.println("revStr" + revStr);
        }
        if(revStr.equals(str))//Don't use ==
        {
         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);
        }
    }
}

The “==” operator

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

Equals() method is defined in Object class in Java and used for checking equality of two object defined by business logic

Imran
  • 429
  • 9
  • 23
0

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

manocha_ak
  • 904
  • 7
  • 19
0

your if condition should be like this

if(revStr.equals(str)){
System.out.println("The string "+str+" is a Palindrome");
         System.out.println(revStr);
}

Because in java == check the address of object not content for more details check below thread

What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Abhishek Mishra
  • 611
  • 4
  • 11