Hello I use 2 different ways to check for a word if its a palindrome or not.. 1 way is hardcoded ( this works as expected ) and the other one I use Stringbuilder for but I always get true and never false as output. I don’t understand why its not working when not hardcoded … here is the code I used for the test. ( the commented variabels work )
public static void main(String[] args) {
StringBuilder a = new StringBuilder("did");
StringBuilder b = a.reverse();
// String a = "did";
// String b = "dad";
if(b.equals(a)) {
System.out.println("true");
}
else {
System.out.println("false");
}
System.out.println(b);
}
Because,
StringBuilder#reversedoes in place reversing. So,a.reverse()also changes the value ofa.You can create a copy of your
StringBuilderrather.You need to use
toString()to compare the contents. usingequalson StringBuilder instances will comparesreferences.