3
String str="inputstring";
StringBuilder sb=new StringBuilder(str);
String rev=sb.reverse().toString();
//System.out.println(sb+" "+rev);             //this prints the same reverse text
if(rev.equals(sb))
  System.out.println("Equal");
else
  System.out.println("Not Equal");

When I print this code StringBuilder and String prints the same output as "gnirtstupni gnirtstupni", but when I checked whether they are equal using if condition they print "Not Equal".

This is really confusing, please explain.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Logesh S
  • 63
  • 4

4 Answers4

3

You are comparing a String and a StringBuilder object. That will never lead to an equal result! The fact that the StringBuilder currently contains the same content as some string doesn't matter!

In other words: assume you got an egg and an egg in a box. Is that box (containing an egg) "equal" to that other egg?!

Theoretically the StringBuilder class could @Override the equals() method to specially check if it is equal to another string. But that would be rather confusing. Because if you would do that, you end up with:

new StringBuilder("a").equals("a") // --> true

giving a different result than:

"a".equals(new StringBuilder("a")) // --> false

Finally: StringBuilder uses the implementation for equals() inherited from java.lang.Object. And this implementation is simply doing a "this == other" check.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

StringBuilder and String are two different classes, so objects of those types should never equal one another, regardless of their content.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • You seem to be implying that objects of different types can't be equal to each other as a rule, which isn't true. – shmosel Aug 13 '17 at 07:05
1

StringBuilder and String are different objects,

But if you want check equal by string. just use toString()

    if(rev.equals(sb.toString()))
      System.out.println("Equal");
    else
      System.out.println("Not Equal");
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
1

rev is a String.

sb is a StringBuilder.

They are two different things, and thus will never be equal.

Joe C
  • 15,324
  • 8
  • 38
  • 50