Explanation of two initialization methods of String

  • 2021-07-18 07:54:09
  • OfStack

There are two ways to create and initialize an String: String str = new String ("abc") or String str = "abc".

1: String str = "abc" The process of creating 1 string

First, look in the constant pool (method area) to see if there is a string object with the content of "abc" If it does not exist, create a string object of "abc" in the constant pool and have str reference it If it exists, let str refer to the object directly

2: String str = new String ("abc") The process of creating a string

First, define a reference of String type of str and store it in the stack See if there is a string object with the content of "abc" in the string constant pool If it exists, skip this step. If it does not exist, create a string object with the content of "abc" in the string constant pool. (The first three steps are completed at compile time.) Perform the new operation to create a specified object "abc" in the heap, where the object in the heap is a copy of the string constant pool "abc" object. Let str point to the object "abc" in the heap (that is, the address in the heap where this object is stored)

Sometimes I ask String str = new String("abc") How many objects will be created by the process of creating 1 string?

Answer: One or two (because compile time checks to see if the string object that needs to be created already exists in the method area constant pool. If there are objects that point references directly to the constant pool, only one object is created in the subsequent runtime heap. If it does not exist, one object is created in the constant pool first, and another object is created in the heap at subsequent runtime, so two objects will be created at this time.)

Summarize


Related articles: