Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 664
Logesh S Avatar asked Apr 17 '26 04:04

Logesh S


2 Answers

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.

like image 126
GhostCat Avatar answered Apr 19 '26 17:04

GhostCat


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

like image 45
Mureinik Avatar answered Apr 19 '26 18:04

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!