Java 字符串对象相等

Java 字符串对象相等,java,string,Java,String,为什么当使用相等运算符“==”进行比较时,使用具有相同字符串文字的字符串类构造函数声明的两个字符串对象不相等,但当通过指定相同字符串文字直接声明时,两个字符串对象相等 String s1 = new String("hello"); String s2 = new String("hello"); Boolean result1 = (s1 == s2);// returns false String s3 = "hello"; String s4 = "hello"; Boolean res

为什么当使用相等运算符“==”进行比较时,使用具有相同字符串文字的字符串类构造函数声明的两个字符串对象不相等,但当通过指定相同字符串文字直接声明时,两个字符串对象相等

String s1 = new String("hello");
String s2 = new String("hello");
Boolean result1 = (s1 == s2);// returns false

String s3 = "hello";
String s4 = "hello";
Boolean result2 = (s3 == s4);// returns true
s1和s2是两个不同的对象,因此引用不相等

在s3期间,对象在字符串池中创建,在s4期间,由于hello已经存在,所以不会创建新对象。因此s4只指向hello对象存在池

现在s3和s4都指向同一个对象,因此引用是相同的


如你所知==检查引用,使其返回true

此答案是对该问题的最佳解释…完全没有必要。请投票以适当的副本结束。