参考:https://www.cnblogs.com/dolphin0520/p/3778589.html
javap -c class文件 可以参看反编译情况
总结:
字符串字面量相加,final修饰的字符串变量加字面量,jvm都会优化成一个字面量
String b = "hello" + 2;
final String b = "hello"; String c = b + 2;
jvm会优化成
String b = "hello2";
final String b = "hello"; String c ="hello2";
字符串变量+字面量会优化成new一个StringBuilder对象append该字面量
如:
String string = "";
for(int i=0;i<10000;i++){
string += "hello";
}
优化成
String string = "";
for(int i=0;i<10000;i++){
StringBuilder str = new StringBuilder(string);
str.append("hello");
str.toString();
}
这里面涉及到的是String.intern方法的使用。在String类中,intern方法是一个本地方法,在JAVA SE6之前,intern方法会在运行时常量池中查找是否存在内容相同的字符串,如果存在则返回指向该字符串的引用,如果不存在,则会将该字符串入池,并返回一个指向该字符串的引用。因此,a和d指向的是同一个对象。
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = new String("hello");
String c = new String("hello");
String d = b.intern();
System.out.println(a==b);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(a==d);
}
}

image.png
StringBuilder扩容机制:默认为16或初始化字符长度+16
append长度不够时扩容,向有位移一位相当于*2

image.png

image.png

image.png