Search code examples
javastringstringbuilder

String Reverse Confusion in java - String - StringBulider


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.


Solution

  • 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.