Home > Java > javaTutorial > Detailed explanation of string constant pool in Java

Detailed explanation of string constant pool in Java

Release: 2018-10-16 17:40:29
forward
2967 people have browsed it

This article brings you a detailed explanation of the string constant pool in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

As the most basic reference data type, Java designers provide a string constant pool for String to improve its performance. So what is the specific principle of the string constant pool? We have the following three Question, to understand the string constant pool:

What is the design intention of the string constant pool?

Where is the string constant pool?

How to operate the string constant pool?

The design idea of ​​the string constant pool

a. The allocation of strings, like other object allocations, is time-consuming and expensive. The space cost, as the most basic data type, is to create a large number of strings frequently, which greatly affects the performance of the program.

b. In order to improve performance and reduce memory overhead, the JVM has made some optimizations when instantiating string constants.

Open a string constant pool for strings, similar to a cache area.

When creating a string constant, first check whether the string exists in the string constant pool.

If the string exists, return the reference instance. If it does not exist, instantiate the string and put it into the pool.

c. Basis of implementation

The basis for realizing this optimization is that strings are immutable and can be shared without worrying about data conflicts.

There is a table in the global string constant pool created by the runtime instance, which always maintains a reference for each unique string object in the pool, which means that they always refer to the string constant pool. Object, so these strings in the constant pool will not be recycled by the garbage collector.

Code: Get the corresponding string from the string constant pool

  String str1 = “hello”;
  String str2 = “hello”;
  System.out.printl("str1 == str2" : str1 == str2 ) //true
Copy after login
Copy after login

Where is the string constant pool

When analyzing the location of the string constant pool, first understand the heap, stack, and method area:

Detailed explanation of string constant pool in Java

Heap

stored It is an object, and each object contains a corresponding class

The JVM has only one heap area (heap) shared by all threads. Basic types and object references are not stored in the heap, only the object itself

The object is recycled by the garbage collector, so the size and life cycle do not need to be determined

Stack

Each thread contains a stack area, and there is only one stack area in the stack Save objects of basic data types and references to custom objects (not objects)

The data in each stack (original types and object references) are private

The stack is divided into 3 Parts: Basic type variable area, execution environment context, operation instruction area (storage operation instructions)

The data size and life cycle can be determined. When there is no reference to the data, the data will automatically disappear

Method area

The static area, like the heap, is shared by all threads

The method area contains things that are always unique in the entire program Elements, such as class, static variables

The string constant pool exists in the method area

Code: The stack method area stores strings

String str1 = “abc”;
String str2 = “abc”;
String str3 = “abc”;
String str4 = new String(“abc”);
String str5 = new String(“abc”);
Copy after login

Detailed explanation of string constant pool in Java

Creation of string objects

Interview question: How many objects are created by String str4 = new String("abc")?

1. Find whether there is an "abc" object in the constant pool

If there is, return the corresponding reference instance

If not, create the corresponding instance object

2. Create a new String("abc") object in the heap

3. Assign the object address to str4 and create a reference

So, there is no "abc" literal in the constant pool Then create two objects, otherwise create an object, and create a reference

Based on the literal, such a variant question is often asked:

String str1 = new String("A" " B") ; How many objects will be created?

String str2 = new String("ABC") "ABC" ; How many objects will be created?

str1:
String constant Pool: "A", "B", "AB": 3
Heap: new String("AB"): 1
Reference: str1: 1
Total: 5

str2:
String constant pool: "ABC": 1
Heap: new String("ABC"): 1
Reference: str2: 1
Total: 3

Code: Basic type variables and constants, variables and references are stored on the stack, and constants are stored in the constant pool

int a1 = 1;
int a2 = 1;
int a3 = 1;
public static int INT1 =1 ;
public static int INT2 =1 ;
public static int INT3 =1 ;
Copy after login

Detailed explanation of string constant pool in Java

How to operate the string constant pool

When JVM instantiates the string constant pool

  String str1 = “hello”;
  String str2 = “hello”;
  System.out.printl("str1 == str2" : str1 == str2 ) //true
Copy after login
Copy after login

String.intern()

通过new操作符创建的字符串对象不指向字符串池中的任何对象,但是可以通过使用字符串的intern()方法来指向其中的某一个。java.lang.String.intern()返回一个保留池字符串,就是一个在全局字符串池中有了一个入口。如果以前没有在全局字符串池中,那么它就会被添加到里面

// Create three strings in three different ways.
    String s1 = "Hello";
    String s2 = new StringBuffer("He").append("llo").toString();
    String s3 = s2.intern();
    // Determine which strings are equivalent using the ==
    // operator
    System.out.println("s1 == s2? " + (s1 == s2)); // false
    System.out.println("s1 == s3? " + (s1 == s3)); // true
Copy after login

字面量和常量池初探

字符串对象内部是用字符数组存储的,那么看下面的例子:

String m = "hello,world";
String n = "hello,world";
String u = new String(m);
String v = new String("hello,world");
Copy after login

1.会分配一个11长度的char数组,并在常量池分配一个由这个char数组组成的字符串,然后由m去引用这个字符串

2.用n去引用常量池里边的字符串,所以和n引用的是同一个对象

3.生成一个新的字符串,但内部的字符数组引用着m内部的字符数组

4.同样会生成一个新的字符串,但内部的字符数组引用常量池里边的字符串内部的字符数组,意思是和u是同样的字符数组

使用图来表示的话,情况就大概是这样的(使用虚线只是表示两者其实没什么特别的关系):

Detailed explanation of string constant pool in Java


测试demo:

 String m = "hello,world";        
 String n = "hello,world";        
 String u = new String(m);        
 String v = new String("hello,world");        
 System.out.println(m == n); //true         
 System.out.println(m == u); //false        
 System.out.println(m == v); //false        
 System.out.println(u == v); //false
Copy after login

结论:

m和n是同一个对象

m,u,v都是不同的对象

m,u,v,n但都使用了同样的字符数组,并且用equal判断的话也会返回true

The above is the detailed content of Detailed explanation of string constant pool in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:java面试笔试微信公众号
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template