0

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");
        }

    }

}
contrapost
  • 673
  • 12
  • 22
  • 1
    It is not ignored. Comparison using `==` just doesn't work how you expected it to work. It compares for object **identity**. And two `String`s are usually different, even if they have the same content. Instead, compare with `String#equals`. – Zabuzard Mar 18 '18 at 21:38
  • In java `==` on objects compares the memory address. Since `Unos` will have a different memory location than another newly instantiated string it will always fail. – vandench Mar 18 '18 at 21:38
  • Please stick to java **naming conventions**. Variable names should always start with a lower case character. So `unos` instead of `Unos`, same with `reversed`. – Zabuzard Mar 18 '18 at 21:39
  • Hi, thank you a lot for your answers. I will use the information all of you provided! – BlueAngel209 Mar 18 '18 at 21:43

1 Answers1

0

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

contrapost
  • 673
  • 12
  • 22
  • Thank you. This was my first Stack Overflow question, and I kind of see now that I shouldn't have asked what the problem with the if statement was, but rather how to compare two strings. – BlueAngel209 Mar 18 '18 at 21:52
  • No problemo. It can be difficult at the beginning so I can recommend to take this tour - https://stackoverflow.com/tour – contrapost Mar 18 '18 at 22:12