What is the difference between String a = "abc"; and String b = new String("abc");

String a = "abc";and String b = new String("abc");both create a string object, but the difference lies in the way they are created.

  • String a = "abc";It is to create a string object through literals. A string constant pool is maintained inside Java. When creating a literal string, the JVM first checks whether the string already exists in the string constant pool, and returns if it exists. Otherwise, create a new string object and put it in the string constant pool, and finally assign the reference of the object to the variable a.
  • String b = new String("abc");newIt is to explicitly create a string object by using keywords. It will first create a new string object in the heap memory, and then check whether the string already exists in the string constant pool. If it exists, no new character will be created . string, otherwise put a new string object into the string constant pool.

Therefore, the main difference between String a = "abc";and String b = new String("abc");is their storage location in memory: the former will reuse the existing string objects in the constant pool as much as possible, while the latter will create a new string object in the heap, and if the string Already exists in the constant pool, the reference of the object in the heap will point to the object in the constant pool.

Guess you like

Origin blog.csdn.net/qq_42133976/article/details/130417011