preface

I wrote an article about the memory partition of the JVM, but I was asked about the location of a String in Java. I remember that String is an immutable quantity, which should be stored in the constant pool, but I asked where a new String should be stored in the heap. Primitive variables and object references are stored on the stack, objects themselves are stored in the heap, explicit String constants are stored in the constant pool, and strings are stored in the heap.

Description of constant pools

The constant pool was previously in the method area, i.e. in the permanent generation, and was moved to the heap starting with JDK7. This change can be seen in the release version of Oracle Notes: ** Important RFEs Addressed in JDK 7 **.

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent 
generation of the Java heap, but are instead allocated in the main part of the 
Java heap (known as the young and old generations), along with the other 
objects created by the application. This change will result in more data 
residing in the main Java heap, and less data in the permanent generation, and 
thus may require heap sizes to be adjusted. Most applications will see only 
relatively small differences inheap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant  differences. RFE: 6962931Copy the code

String Description of memory location

1. Explicit String constants

String a = "holten";
String b = "holten";
Copy the code
  • The first line of code creates a String with the value holten in the constant pool.
  • When the second statement is executed, no new String is created because there is a Holten in the constant pool.
  • The reference to the string is in the vm stack.

2. The String object

String a = new String("holtenObj");
String b = new String("holtenObj");
Copy the code
  • When Class is loaded, a String object with the value holtenObj is created in the constant pool. When the first sentence is executed, a new String(“holtenObj”) object is created in the heap.
  • When executing the second statement, instead of creating a new String because there is a holtenObj in the constant pool, create a new String(“holtenObj”) object in the heap.

verify

/** * Created by holten.gao on 2016/8/16. */
public class Main {
    public static void main(String[] args){
        String str1 = "Gao Xiaotian";
        String str2 = "Gao Xiaotian";
        System.out.println(str1==str2);//true
        
        String str3 = new String(Big Sky);
        String str4 = new String(Big Sky);
        System.out.println(str3==str4);//false}}Copy the code

Return result:

true
false
Copy the code

Scan the qr code below on wechat and follow our official account for more articles