==运算符在java中是如何工作的
在上述代码中,s1和s2均指字符串“hi”。但是为什么程序的输出是-‘s1和s2不相等’?谢谢试试看==运算符在java中是如何工作的,java,Java,在上述代码中,s1和s2均指字符串“hi”。但是为什么程序的输出是-‘s1和s2不相等’?谢谢试试看 public class StrEqual { public static void main(String[] args) { String s1 = "hi"; String s2 = new String("hi"); System.out.println(s1); System.out.println(s2);
public class StrEqual {
public static void main(String[] args) {
String s1 = "hi";
String s2 = new String("hi");
System.out.println(s1);
System.out.println(s2);
if(s1 == s2){
System.out.println("s1 and s2 are equal");
}
else{
System.out.println("s1 and s2 are not equal");
}
}
}
s1==s2
比较对象引用,而不是字符串内容。操作符比较对象引用,即它们在内存中的位置。这就像比较指针。要获得“深度”相等,您需要使用等于方法。@SotiriosDelimanolis这是它的副本吗?搜索“java比较字符串”。它的工作原理与=
完全相同。
s1.equals(s2);