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
  • 90,369
  • 161
  • 124
  • 175
Logesh S
  • 63
  • 3

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
  • 133,361
  • 24
  • 165
  • 234
1

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

Mureinik
  • 277,661
  • 50
  • 283
  • 320
  • 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");
user7294900
  • 52,490
  • 20
  • 92
  • 189
1

rev is a String.

sb is a StringBuilder.

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

Joe C
  • 14,676
  • 8
  • 38
  • 49