-1

I wrote this method to check if the given string is a palindrome or not and depending on the result I implemented an if-else statement to print out something. I know the string is a palindrome but the result I am getting is different from what I expected. Here is the java code:

public class Palindrom {
    public static void main(String[] args){
        String palindrome = "DOT SAW I WAS TOD";
        String result = "";

        for(int i = palindrome.length() - 1; i > 0; i--){
            result = result + palindrome.charAt(i);
        }
        if (result == palindrome){
            System.out.println("Yes it is a palindrome");
        } else {
            System.out.println("No it is not palindrome");
        }
    }

} //No it is not palindrome

What I suspected the problem is on result == palindrome. Is this getting false because I am comparing two different objects? What method should I use to solve such problems?

vbence
  • 20,084
  • 9
  • 69
  • 118
Tesfa Zelalem
  • 619
  • 1
  • 9
  • 18

3 Answers3

3

You should not use "==".

result.equals(palindrome);

try this

public class Palindrom {
    public static void main(String[] args){
        String palindrome = "DOT SAW I WAS TOD";
        String result = "";

        for(int i = palindrome.length() - 1; i >= 0; i--){
            result = result + palindrome.charAt(i);
        }

        if (result.equals(palindrome)){
            System.out.println("Yes it is a palindrome");
        }else{
            System.out.println("No it is not palindrome");
        }
    }

}

you have to decrement till i>=0

Siva Kumar
  • 1,983
  • 3
  • 14
  • 26
1

You have to use equals on strings instead of ==

result.equals(palindrome);
Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
1

You cannot use == in Java when comparing strings, you have to use String.equals(String), in this case

result.equals(palindrome);

Benedikt
  • 136
  • 1
  • 10