Search code examples
javaeclipseif-statementpalindrome

Why is this if statement in my code ignored?


This code is supposed to reverse a String and then check with if statement if the original String input equals the reversed input. But the if statement never runs, indicating that original String and reversed one aren't the same... even when I input a palindrome.

import java.util.Scanner;

public class TestScannerPalindrome {
    static String reverse(String par) {
        String reversed = new String();
        for(int i = par.length() - 1; i >= 0; i--) {
            reversed += par.charAt(i);
        }
        return reversed;
    }
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        String unos = sc.nextLine();
        if(unos == reverse(unos)) {
            System.out.println(unos + " is palindrome");
        } else {
            System.out.println(unos + " is not palindrome");
        }

    }

}

Solution

  • Strings are objects in Java so you can't compare them using '==' operator. You have to use equals() method of the String class.