检查,如果字符串中使用==
问题描述:
当我执行下面的代码是Java相等,输出为“假”检查,如果字符串中使用==
String string1 = new String("ABC");
String string2= new String("ABC");
System.out.println(string1==string2);
然而,当我不使用String类的构造函数的输出是“真”
String string1;
String string2;
string1="ABC";
string2= "ABC";
System.out.println(string1==string2);
我知道它更好地使用.equals()方法,但为什么输出差异?
答
始终使用等于自==
并不总是奏效。即使对象在内存中相同,它也可能存储在不同的地方,并且==
检查对象身份而不是相等。