Learning others summary record, relatively shallow, there may be problems, welcome to correct.

String, StringBuilder, StringBuffer

  • Strings are final, so strings cannot be modified. For String a = “hello “+ “world”; String has not changed, only the reference address of A has changed.
  • StringBuilder and StringBuffer are used when string references are frequently modified. A StringBuffer is thread-safe (synchronized modified) and less efficient than a StringBuilder. So a single thread uses stringBuilder.append ().
  • String addition generates a StringBuilder object underneath, calls AppEnd, and toString returns a String

String.intern()

Premise: Intern creates a string object in the constant pool if it does not exist and returns the reference address. The hotspot virtual machine implements the method area through persistent generation, jdk1.6 where constant pool is stored in persistent generation and 1.7 where constant pool is moved to the heap. In jdk1.7, if string objects do not exist in the constant pool and exist in the heap, then string objects are not created in the constant pool.

Frequently seen exam

String s1 = new String(“abc”); This statement creates several objects. The first object, the content “ABC”, is stored in the constant pool. The second object, the content “ABC”, is stored in the heap.

String s2 = new String(“ab”) + new String(“ab”); This statement creates several objects. Four objects in the heap: “ab” “ab” “abab”. Constant pool: “ab”.

Program run to see the result

public class Demo {

	public static void main(String[] args) {
		test1();// false false
		test2();// false true            
	}

	public static void test1(a) {
		String s = new String("1");
		s.intern();
		String s2 = "1";
		System.out.println(s == s2);

		String s3 = new String("1") + new String("1");
		s3.intern();
		String s4 = "11";
		System.out.println(s3 == s4);
	}

	public static void test2(a) {
		String s = new String("1");
		String s2 = "1";
		s.intern();
		System.out.println(s == s2);

		String s3 = new String("1") + new String("1");
		String s4 = "11"; s3.intern(); System.out.println(s3 == s4); }}Copy the code