String s1 = new String("Hello!");这是在堆中创建了对象,将堆中的对象地址赋值给了s1
String s2 = "Hello!"是在常量池中找有没有这个值,没有就创建,有就把常量池中的地址赋值给s2
1.两种都new了对象
代码:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = new String("hello");//s1直接new了字符串对象
String s2 = new String("hello");//s2也new了字符串对象
System.out.println(s1 == s2);//false
System.out.println(s1.equals(s2));//true
}
}
结果:

2. s1new了对象,s2没有
代码:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = new String("hello");//s1new了对象
String s2 ="hello";//s2直接赋值
System.out.println(s1 == s2);//false
System.out.println(s1.equals(s2));//true
}
}结果:

3.s1没有new对象,s2new了对象
代码:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 ="hello";//s1直接赋值
String s2 = new String("hello");//s2new了对象
System.out.println(s1 == s2);//false
System.out.println(s1.equals(s2));//true
}
}
结果:

4.s1和s2都直接赋值
代码:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 ="hello";//s1直接赋值
String s2 = "hello";//s2也直接赋值
System.out.println(s1 == s2);//true
System.out.println(s1.equals(s2));//true
}
}
截图:

版权声明:本文为weixin_42454041原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。