The following code did not work. Can anyone tell me what's wrong with the following code. Logically it should work...
package assignments; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class IsPalindrome { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter a Word:"); StringBuffer sb1 = new StringBuffer(br.readLine()); StringBuffer sb2 = new StringBuffer(sb1); sb1.reverse(); if(sb2.equals(sb1)) System.out.println("Palindrome"); else System.out.println("Not a Palindrome"); } }
StringBuilderinstead ofStringBuffer(if you don't access it from multiple threads), as it's faster.StringBufferdoesn't overrideequals()inherited fromObjectso contents in theStringBufferaint compared just their reference.