-1

Below is the code in Java:

package string;

import java.util.Scanner;

public class PalindromeString 
{
    public static void main(String[] args) 
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string: ");
        String s=sc.next();
        StringBuilder j=new StringBuilder(s).reverse();
        System.out.println(j);
        boolean b=s.equals(j);
        System.out.println(b);
        sc.close();
    }
}

Output: Enter the string: madam

j=madam

false

Why the output is false for this code?

Alex Butenko
  • 3,664
  • 3
  • 35
  • 54
  • 1
    StringBuilder is not a String class, so it should not be equals, – Shen Yudong Jan 25 '18 at 02:19
  • Note that `StringBuilder` is an utility object in order to create `String` objects, it is not a `String` itself. It is a bit like comparing *chocolate* to a *chocolate factory*. While *chocolate factories* produce *chocolate*, they are not *chocolate* themselves. – Zabuzard Jan 25 '18 at 02:38

4 Answers4

3

The output is false because you're comparing a String object to a StringBuilder object. Although both s and j contain the same data, they are different object types, so they are never "equal". To make the answer true, you could change j so it's a String instead of a StringBuilder:

String j = new StringBuilder(s).reverse().toString();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rich Dougherty
  • 3,231
  • 21
  • 24
2

The reason the result is false is stated clearly in the String.equals() documentation:

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

You are passing a StringBuilder object to equals() instead of a String object, so the result is false, regardless of the characters.

String and StringBuilder both implement CharSequence, so you can use String.contentEquals() instead:

boolean b = s.contentEquals(j);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

You are comparing a String to a StringBuilder. Of course it would be false.

Try b=s.equals(j.toString()); This should makes b true.

Nin
  • 375
  • 1
  • 11
0

stringBuilder does not override Object's .equals() function, which means the two references are not the same and the result is false.

Greg Artisi
  • 172
  • 2
  • 12