在Java中equals()vs ==
为了检查equals()
和==之间的区别,让我们采用三个字符串。
String str1 = "Test"; String str2 = new String(str1); String str3 = "Demo";
让我们检查一下equals()
System.out.println(str1 + " equals " + str2 + " ? " + str1.equals(str2)); System.out.println(str1 + " equals " + str3 + " ? " + str1.equals(str3));
现在,我们将使用==检查它们
System.out.println(str1 + " == " + str2 + " ? " + (str1 == str2)); System.out.println(str1 + " == " + str3 + " ? " + (str1 == str3));
以下是最终示例,其输出将相应地进行区分。
示例
public class Demo { public static void main(String[] args) { String str1 = "Test"; String str2 = new String(str1); String str3 = "Demo"; System.out.println(str1 + " equals " + str2 + " ? " + str1.equals(str2)); System.out.println(str1 + " == " + str2 + " ? " + (str1 == str2)); System.out.println(str1 + " equals " + str3 + " ? " + str1.equals(str3)); System.out.println(str1 + " == " + str3 + " ? " + (str1 == str3)); }}
输出结果
Test equals Test ? true Test == Test ? false Test equals Demo ? false Test == Demo ? false