字串初始化

  1. String Literal:JVM looks in the String pool to find if any other String is stored with same value.If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

     String str1 = “abc”;
    
  2. New Operaor:JVM creates the String object in heap but don’t store it into the String Pool.

     String str = new String(“abc”);
    

    這樣宣告會產生兩個物件:

    1.在string pool產生常數字串"abc"

    1. 字串物件str
  3. intern(): When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    JDK 1.7後,如果在string pool找不到,不會複製字串物件,是把字串的reference加到string pool。

from: All About String in Java

Test

public class StringTest {
    public static void main(String[] args) {
        String s1 = "abc"; 
        String s2 = new String("abc");
        String s3 = s2.intern();

        System.out.println("s1 == s2 : " + (s1 == s2));
        // true: 都指向String Pool裡的"abc"
        System.out.println("s1 == s3 : " + (s1 == s3));

        String s4 = new String("abc") + new String("xyz");
        String s5 = s4.intern();
        // true: 都指向Heap裡的 "abcxyz"
        System.out.println("s4 == s5 : " + (s4 == s5));
    }
}
s1 == s2 : false
s1 == s3 : true
s4 == s5 : true

results matching ""

    No results matching ""