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
Where is the string constant pool
When analyzing the location of the string constant pool, first understand the heap, stack, and method area:
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”);
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 ;
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
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
字面量和常量池初探
字符串对象内部是用字符数组存储的,那么看下面的例子:
String m = "hello,world"; String n = "hello,world"; String u = new String(m); String v = new String("hello,world");
1.会分配一个11长度的char数组,并在常量池分配一个由这个char数组组成的字符串,然后由m去引用这个字符串
2.用n去引用常量池里边的字符串,所以和n引用的是同一个对象
3.生成一个新的字符串,但内部的字符数组引用着m内部的字符数组
4.同样会生成一个新的字符串,但内部的字符数组引用常量池里边的字符串内部的字符数组,意思是和u是同样的字符数组
使用图来表示的话,情况就大概是这样的(使用虚线只是表示两者其实没什么特别的关系):
测试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
结论:
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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.