堆栈常量池

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在常量池中存放
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值