Home Java javaTutorial Detailed explanation of string constant pool in Java

Detailed explanation of string constant pool in Java

Oct 16, 2018 pm 05:01 PM
java string

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles