0

import java.util.Scanner;

class Pal {
    public static boolean Palindrome(StringBuffer str) {
        StringBuffer str1 = str.reverse();
        System.out.println(str1);
        if (str == str1) {
            return true;
        } else { 
            return false;
        }
    }

    public static void main(String args[]) {
        System.out.println("Enter a string");

        StringBuffer str = new StringBuffer();
        Scanner input = new Scanner(System.in);
        str.append(input.nextLine());

        boolean result = Palindrome(str);
        System.out.println(result);
    }
}

How sholud I improve my code such that values come out to be perfectly correct?

eloibm
  • 899
  • 2
  • 11
  • 27

1 Answers1

1
if (str == str1)
{
  return true;
}
else
{ 
  return false;
}

is the same as

return str == str1;

However, this still "won't work" correctly because

  1. Code should equals() for comparing objects (including Strings and StringBuffers) and

  2. StringBuffer does not have a useful equals.

A correction, taking both of these into account, would be:

return str.toString().equals(str2.toString());

In this case we first get the current String content of both StringBuffer objects and then compare it with String.equals(String), which works as expected.

An alternative would be to bypass the StringBuffers in this case and directly use Strings; this would allow skipping the toString calls.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220