使用equals方法可以比较两个字符串是否相等,因为String重写了Object的equals方法,而==运算符比较两个对象引用是否相同的实例。
public class TestToString {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";//String s2 = new String("hello");改成这样的话,它又是false了。 System.out.println(s1 == s2);//那我觉得这应该是false呀??为什么它是true????
}
}
大惑不解中。
public class TestToString {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";//String s2 = new String("hello");改成这样的话,它又是false了。 System.out.println(s1 == s2);//那我觉得这应该是false呀??为什么它是true????
}
}
大惑不解中。
执行这个的时候会先在字符串池中寻找有没有"hello"这个字符串,有的话则直接指向那个地址,这里就直接指向了s1的地址String s2 = new String("hello");
这个则不管有没有,直接开辟空间
而 == 比较的是引用指向的内存地址
new Stirng(“hello”)是创建了一个实例 指的内存地址不一致 所以返回 false
建议去看看Stirng 的源代码 了解了解