'Program to find if a string is a palindrome keeps on failing. Even after using toLowerCase() command for both strings, output doesn't come

import java.util.Scanner;
class Palindrome_string
{
    public static void main()
    {
        System.out.println("\f");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string");
        String a = sc.nextLine();
        int b = a.length();
        String rev = "";
        for (int i = b - 1; i >= 0; i--)
        {
            char c = a.charAt(i);
            rev = rev + c;
        }
        System.out.println("Original word "+a);
        System.out.println("Reversed word "+rev);
        a = a.toLowerCase();
        rev = rev.toLowerCase();
        if (a == rev)
        {
            System.out.println("It is a palindrome");
        }
        else
        {
            System.out.println("It is not a palindrome");
        }
        sc.close();
    }
}

The program compiles properly. Still, when running the program, the message which tells if it is a palindrome prints incorrectly. What changes do I make? Here is a picture of the output. Even though the word 'level' (which is a palindrome) has been inputted, it shows that it isn't a palindrome. What changes should I make? output pic



Solution 1:[1]

You should not use == to compare two strings because it compares the reference of the string, i.e. whether they are the same object or not. Use .equals() instead. It tests for value equality. So in your case:

if (a.equals(rev))
{
    System.out.println("It is a palindrome");
}

Also try not to use single-letter variable names except for index variables when iterating over a list etc. It's bad practice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cooper