The storage method of String data in Java.

In Java, data of type String is stored in a string pool. The string pool is a special region within the Java heap memory used to store string constant objects.

When we use string literals to create a String object, the JVM first checks if an object with the same value already exists in the string constant pool. If it does, it returns a reference to that object. If not, it creates a new string object in the constant pool and returns a reference to it.

For example, in the following code, both str1 and str2 are references to the same string object in the string constant pool.

String str1 = "hello";
String str2 = "hello";

When a String object is created using the new keyword, the JVM will allocate a new string object in the heap memory, regardless of whether there is a string object with the same value in the string constant pool. Therefore, in the following code, str3 and str4 point to different string objects in the heap memory.

String str3 = new String("hello");
String str4 = new String("hello");

It is important to note that string objects in the string constant pool are immutable, meaning once a string object is created, its value cannot be changed. If a string object is modified, a new string object is actually created.

In order to improve the efficiency of comparing strings, Java also offers the intern() method for the string constant pool. By calling this method, a string object can be added to the string constant pool. If a string object with the same value already exists in the pool, the method will return a reference to that object. Otherwise, the object will be added to the pool and a reference to it will be returned. For example:

String str5 = new String("hello").intern();
String str6 = "hello";
System.out.println(str5 == str6);  // 输出true

By invoking the intern() method, the value of str5 is added to the string constant pool, so str5 and str6 point to the same string object.

bannerAds