Search code examples
javareversepalindrome

How to make Palindrome Program?


I tried to reverse the inputed String, and output "This is a Palindrome." when the input is equal to its reverse.

The reverse part is correct, but it keeps saying it is not equal, even though I entered a Palindrome number. How do I fix this??

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    System.out.println("Enter a sequence of numbers: ");
    String sequence = scanner.next();
    
    char[] array = new char[sequence.length()];
    int numberIndex = 0;
            
    String reverse = "";
    
    for (int i = sequence.length() - 1; i >= 0; i--) {
        array[numberIndex] = sequence.charAt(i);
        
        numberIndex++;
    }
    
    for (int i = 0; i < sequence.length(); i++) {
        reverse += array[i];
    }
    
    System.out.println(reverse);
    
    if (sequence == reverse) {
        System.out.println("This number is a palindrome.");
    } else {
        System.out.println("This number is not a palindrome.");
    }
    
}

Solution

  • Try using the equals method for the string comparison.

    Instead of this if (sequence == reverse) {

    Use this if (sequence.equals(reverse)) {

    The reason is that == checks for reference equality, that is "sequence" and "reverse" which are reference to strings and are pointing to memory locations in the heap memory region of the JVM, are checked for being the same reference. And since "sequence" and "reverse" are two different variable names to different objects on the heap, obviously they can be same.

    And you don't want to check that.

    Instead what you intend to do is that whether the original string referenced by the variable name "sequence" is equal in content with the reversed string having the reference "reverse".

    This equals() method checks whether the two referenced objects are not null, they are of the same type as well as equal in content.

    If al the above parameters are the same then equals will return true, otherwise false.

    Hence equals() method should be used here.