Palindrome Checker Java

I’m trying to create a palindrome checker but it doesn’t print the right result even if the input string and the reversed string is the same.

I was expecting to see if the input string is a palindrome or not.

import java.util.Scanner;

public class palindrome {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a;
        System.out.println("Please input the string: ");
        a = scanner.next();
        String reversedString = "";
        for(int i = a.length()-1; i>=0; i--){
            reversedString = reversedString + a.charAt(i);
        }
        if((reversedString.toUpperCase()) == (a.toUpperCase())) {
            System.out.println("It is a palindrome.");
        }
        else {
            System.out.println("It is not a palindrome.");
        }
        System.out.println(a.toUpperCase());
        System.out.println(reversedString.toUpperCase());
    scanner.close();
    }
}

>Solution :

The issue with your code is that you are using the == operator to compare the original string and the reversed string. This operator compares the memory addresses of the two strings, rather than their contents. To compare the contents of the two strings, you should use the .equals() method or the .equalsIgnoreCase() method.

Here’s an updated version of the code that uses the .equalsIgnoreCase() method to compare the original string and the reversed string:

import java.util.Scanner;

public class palindrome {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a;
        System.out.println("Please input the string: ");
        a = scanner.next();
        String reversedString = "";
        for(int i = a.length()-1; i>=0; i--){
            reversedString = reversedString + a.charAt(i);
        }
        if(reversedString.equalsIgnoreCase(a)) {
            System.out.println("It is a palindrome.");
        }
        else {
            System.out.println("It is not a palindrome.");
        }
        scanner.close();
    }
}

By using the .equalsIgnoreCase() method, you are comparing the contents of the two strings, regardless of the case of the letters. This way you can check if the input string is palindrome or not.

Leave a Reply