public class q {
public static void main(String[] args) {
String a="hello";
String b="hello";
System.out.println(a==b);//true
//先在栈中创建一个对String类的对象引用变量a,然后查找栈中有没有存放"hello",如果没有,
//则将"hello"存放进栈,并令a指向"hello",如果已经有"hello"则直接令a指向"hello"
String x=new String("hello");
String y=new String("hello");
System.out.println(x==y);//false
System.out.println(x==a);//false
//用new()来新建对象的,它会在存放于堆中。每调用一次就会创建一个新的对象。
final String w="hello2";
String z="hello"+"2";
String c=a+2;
String d=b+2;
System.out.println(z==w);//true,存放在常量池
System.out.println(c==z);//false
System.out.println(c==d);//false
//java对String相加是通过StringBuffer实现的,先构造一个StringBuffer里面存放"hello"
//然后调用append()方法追加"2",然后将值为"hello2"的StringBuffer转化为String对象,指向堆中的String对象
final String e="hello";
String g="hello2";
String f=e+2;
System.out.println(e==a);//true,存放在常量池
System.out.println(f==w);//true,得到的f是final型的
System.out.println(f==g);//true,e是final修饰,e+2得到的f指向了在常量池中的g
System.out.println(c==g);//false,a+2是通过StringBuffer实现的,拼接的c没有指向常量池,指向堆
System.out.println(c==f);//false
//final用来修饰数据,只能赋值一次且值无法再改变
//a==b==e在常量池中存放
//w==z==g==f在常量池中存放
}
}