String comparison with logical operator in Java

前端 未结 7 1117
别那么骄傲
别那么骄傲 2020-12-03 23:59

When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo

7条回答
  •  感情败类
    2020-12-04 00:13

    == compares the object references, equals() compares the values of the Strings.

    In your case you are allocating two String objects both with value "hello", then comparing them with ==. The compiler may decide to optimise and use the same object reference, giving a true result like the one you got. However this is not guaranteed behaviour - it is much safer to use equals() for value comparison.

提交回复
热议问题