0

'''' while comparing the reverse of the string to the original It return TRUE instead of FALSE ''''

    import java.io.*;
    import java.lang.StringBuilder;
    import java.util.*;
    
    public class test {

        public static void main(String[] args) {
            String A = "java";
            StringBuilder str = new StringBuilder();
            str.append(A);
            System.out.println(str);
            System.out.println(str.reverse());
            System.out.println(str == str.reverse());
            if (str.equals(str.reverse())) {
                System.out.println("Yes");
            } else {
                System.out.println("No");
            }
        }

}

Mohan S
  • 1
  • 2

1 Answers1

0

The equals method is shorting out on object equality, not value equality. This will get what you're aiming for.

if (str.toString().equals(str.reverse().toString())) {
    System.out.println("Yes");
} else {
   System.out.println("No");
}
Ryan
  • 1,762
  • 6
  • 11
  • oh, so we need to convert the StringBuilder str to a normal String.??? – Mohan S Jul 29 '21 at 16:27
  • Yes, or to a different StringBuilder. If you look at most equals() methods, the first line is usually a direct object comparison. Since you're comparing the same object, as opposed to the value of that object, it's returning true. – Ryan Jul 29 '21 at 16:49