StringTable common interview questions analysis

Signature: But do good deeds, don't ask about the future.

Article directory


foreword

Record the analysis of StringTable common interview questions.


Features of StringTable:

  • The string in the constant pool is only a symbol, and it becomes an object when it is used for the first time
  • String constant objects are stored in the string pool
  • Use the string pool mechanism to avoid repeated creation of string objects
  • The principle of string variable splicing is StringBuilder (1.8)
  • The principle of string constant splicing is compile-time optimization

Look at the code first:

public class StringTableDemo {
    
    
    // StringTable []  串池 hashtable结构,不能扩容
    public static void main(String[] args) {
    
    
        String s1 = "a";
        String s2 = "b";
        String s3 = "ab"; // StringTable ["a","b","ab"] 当代码执行到这一步,"a","b","ab" 都被加载到串池中

        String s4 = s1 + s2; // new StringBuilder().append("a").append("b").toString() => new String("ab") 我们知道,new出来的对象都存在堆中
        System.out.println(s3 == s4); // 堆中的s4和串池中的s3不是同一个对象,所以结果是:false

        // javac 在编译期间的优化,两个常量字符串"a"和"b"的拼接结果就是字符串"ab"
        String s5 = "a" + "b"; // 当代码执行到这一步,会先去串池中找有没有“ab”字符串对象,没有的话,将“ab”字符串加入串池;有的话,直接引用串池中的“ab”对象
        System.out.println(s3 == s5); // s3和s5都是指向串池中的“ab”字符串对象,所以结果是:true
    }
}

operation result:

insert image description here


Summarize

The blog mainly records the analysis of common interview questions in StringTable. Please correct me if there are any mistakes or deficiencies. If it is helpful to you, please click three times.

Guess you like

Origin blog.csdn.net/YangCunle/article/details/129798139