String字符串拼接

结论:常量与常量的拼接结果在常量池,且常量池中不会存在相同内容的常量。

   只要其中有一个是变量,结果就在堆中。

   如果拼接结果调用intern()方法,返回值就在常量池中。

// 示例

import org.junit.Test;

/**
* @auto dh
* @create 2020-03-24-12:16
*/
public class StringDemo003 {
@Test
public void SDemo(){
String s1="hello";
String s2="World";
String s3="helloWorld";
String s4=s1+"World";
String s5="hello"+s2;
String s6=s1+s2;
String s7="hello"+"World";
String s8=(s1+s2).intern();
System.out.println(s3==s4);//false
System.out.println(s3==s5);//false
System.out.println(s3==s6);//false
System.out.println(s3==s7);//true
System.out.println(s3==s8);//true
}
}

猜你喜欢

转载自www.cnblogs.com/kukai/p/12558212.html