一.String s=new String("abc");//产生几个对象 答案:2个。heap中一个,String pool中一个。 二.String s="abc"; String s1=new String("abc");//该条语句却只产生了一个String对象。 三.String s1=new String("abc"); String s2="abc"; String s3=new String("abc"); String s4="abc"; 问题:s1==s2?//false s1==s3?//flase s2==s3?//false s2==s4?//true 4.String hello="hello"; String hel="hel"; String lo="lo"; System.out.println(hello=="hel"+"lo");//true (在编译阶段就能确定) System.out.println(hello=="hel"+lo);//false (在运行时才能确定)
5.String s = "a" + "b" + "c";产生几个对象? 很多人会认为是3,4,5个。但实际上仅产生一个对象。在String pool中的"abc"。因为s的值在编译阶段就能确定。
总结:java中,String通常分配在两个地方,一个地方是内存堆中,一个是Stirng pool(因为String的通用性而设计的)。弄清楚这两个方面,问题即迎刃而解。 |