0
public class testing {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        sb.append(str);
        sb1.append(str);
        sb1.reverse();
        if(sb == sb1) {
            System.out.println("yes");
        }else if(sb != sb1) {
            System.out.println("no");
        }
        System.out.println(sb.length());
        System.out.println(sb1.length());
        sc.close();
    }
}

Everything working fine including string reverse, but always getting no as result.

Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
  • `==` is reference equality. – Michael Jun 03 '19 at 08:20
  • As an aside, don't use `if (condition) { ... } else if (!condition) { ... }`, unless you actually expect that condition to have changed. Just use `else`. – Andy Turner Jun 03 '19 at 08:21
  • `sb == sb1` - you're comparing if it is the same object - it will never be. What's worse, you're comparing StringBuilders, not String. You should get String from them first and then compare using `equals()` method instead. – Amongalen Jun 03 '19 at 08:22
  • @AndyTurner *"unless you actually expect that condition to have changed"* — What do you mean? Do you mean that the result of `sb == sb1` could have changed within the `if` branch? – MC Emperor Jul 12 '21 at 10:09
  • @MCEmporer in this case, it can't have changed because they are local non-published variables; but in the general case of there is no guarantee that two syntactically-identical expressions evaluate to the same value. So, if you mean "if condition do this, otherwise that", use if/else, not if condition/else if not condition. – Andy Turner Jul 12 '21 at 15:42

1 Answers1

0

You will always get no because StringBuilder creates new object & as you are using == for comparison, it compares reference only not content of StringBuilder object, so if you want to compare content you have to use .equals() method after applying .toString() on StringBuilder object.

  • Had to check it to confirm - you can't compare `StringBuilder`s with `equals()` - will return false even if the content is the same. You have to get Strings from them before comparing. – Amongalen Jun 03 '19 at 08:34