1

I am checking if a String "nitin" is a palindrome but it's returning false.

Please anyone help me to shorout this.

public static void main(String[] args) { StringBuffer sb = new StringBuffer("nitin"); sb.reverse(); String rev = sb.toString(); System.out.println(sb); System.out.println(rev); if (sb.equals(rev)) { System.out.println("true"); } else { System.out.println("false"); } } 
1

3 Answers 3

4

You are comparing the StringBuffer with the String. Try with if (sb.toString().equals(rev)) {

Sign up to request clarification or add additional context in comments.

1 Comment

In addition, there is also a mistake in regards to the str.reverse() part that I addressed.
1

sb is a StringBuffer, rev is a String. These two objects of different types cannot be compared for "String value equality" with each other.

Use if (sb.toString().equals(rev)): this way you compare if two strings are equal, as sb.toString() is converted to a String.

Also, it is wrong at the beginning to reverse sb. That is because at the time you declare String rev = sb.toString(), sb is already reversed. Unreverse sb by calling sb.reverse() again after declaring rev. Your final code should be

 StringBuffer sb = new StringBuffer("nitdin"); sb.reverse(); // reversed sb String rev = sb.toString(); // rev is reversed sb to String sb.reverse(); // unreversed sb ... if (sb.toString().equals(rev)) // String-string comparison 

3 Comments

String rev=sb.toString(); check this line
"They cannot be compared." - They can. And the fact that they can is the cause of OPs problem. It is just always false.
@Mulliganaceous Why is it "not useful"? When is a comparision "useful"? I would tend to choose a neutral wording.
0

You might misunderstand the StringBuffer and String. Your code might need to change

 StringBuffer sb=new StringBuffer("nitin"); String before = sb.toString(); sb.reverse(); String after = sb.toString(); System.out.println(before); System.out.println(after); System.out.println(before == after); if(before.equals(after)){ System.out.println("true"); }else{ System.out.println("false"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.