**
1.String s=new String(“hello”);的创建过程:
**
**
2.String s=new String(“hello”);的创建过程**
**
3.代码测试**
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); //true
System.out.println(s1.equals(s2));//true
String s3="hello";
String s4=new String("hello");
String s41=new String("hello");
System.out.println(s3==s4); //false
System.out.println(s3.equals(s4)); //true
System.out.println(s4==s41);//false
String s5="hello";
String s6="h"+"ello";
String s7="h";
String s8="ello";
String s9=s7+s8;
System.out.println(s5==s6);//true
System.out.println(s5==s9);//false
String s10=new String("hello");
String s11="h"+new String("ello");
String s12=new String("h")+new String("ello");
String s13="hello";
System.out.println(s10.intern()==s13);//true
System.out.println(s11.intern()==s13);//true
System.out.println(s12.intern()==s13);//true
总结:
1.使用直接赋值的方式,直接在常量池中进行寻找,找到了就直接把把这个地址值赋值给变量,否则先在常量池中创建,然后把地址值再进行赋值。
2.new String(“hello”);需要创建两个对象,new关键字创建时,前面的操作和字面量创建一样,只不过最后在运行时会创建一个新对象,变量所引用的都是这个新对象的地址。
3.equals()方法本来比较的两个对象的地址值,但是String类重写了父类的方法,用来去比较两个字符串字符串字面上的内容是否相同