String的声明
String的声明
public class StringTest {
@Test
public void test4(){
String s1 = "helloworld";
String s2 = "world";
String s3 = "hello"+s2;
System.out.println(s1 == s3);//false
final String s4 = "world";
String s5 = "hello"+s4;
System.out.println(s1 == s5);//true
}
/*
结论:
1.常量与常量的拼接结果在常量池中,且常量池中不会存在相同内容的常量
2.只要其中有一个是变量,结果就在堆中
3.如果拼接的结果调用intern(),返回值就在常量池中
*/
@Test
public void test3(){
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = "hello" + "world";
String s5 = s1 + "world";
String s6 = "hello" + s2;
String s7 = s1 + s2;
String s8 = s5.intern();//返回值得到的s8使用的是常量池中已经存在的“helloworld”
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s7);//false
System.out.println(s3 == s8);//true
}
/*
String的实例化方式:
方式一:通过字面量定义的方式
方式二:通过new + 构造器的方式
*/
@Test
public void Test2(){
//通过字面量定义的方式,此时的s1和s2的数据JavaEE声明在方法区中的字符串常量池中
String s1 = "JavaEE";
String s2 = "JavaEE";
//通过new+构造器的方式:此时的s3和s4保存的是地址值,是数据在堆空间中开辟空间以后对应的地址值
String s3 = new String("JavaEE");
String s4 = new String("JavaEE");
System.out.println(s1