0

Java Noob here, I wrote the following code to check if a given string is palindrome or not:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);
        String A=sc.next();

        StringBuilder str = new StringBuilder(A);
        StringBuilder original = new StringBuilder(A);
        str.reverse();
        if(str == original)
        {
            System.out.println("Yes");
        }

        else
            System.out.println("No");
    }
}

for input 'madam' it's saying NO? What is wrong with the code?

  • 3
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Alex May 23 '21 at 13:11
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels May 23 '21 at 13:11

0 Answers0