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

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”);

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 ;

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

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是同样的字符数组

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

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

结论:

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1510
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Java Virtual Threads Performance Benchmarking Java Virtual Threads Performance Benchmarking Jul 21, 2025 am 03:17 AM

Virtual threads have significant performance advantages in highly concurrency and IO-intensive scenarios, but attention should be paid to the test methods and applicable scenarios. 1. Correct tests should simulate real business, especially IO blocking scenarios, and use tools such as JMH or Gatling to compare platform threads; 2. The throughput gap is obvious, and it can be several times to ten times higher than 100,000 concurrent requests, because it is lighter and efficient in scheduling; 3. During the test, it is necessary to avoid blindly pursuing high concurrency numbers, adapting to non-blocking IO models, and paying attention to monitoring indicators such as latency and GC; 4. In actual applications, it is suitable for web backend, asynchronous task processing and a large number of concurrent IO scenarios, while CPU-intensive tasks are still suitable for platform threads or ForkJoinPool.

how to set JAVA_HOME environment variable in windows how to set JAVA_HOME environment variable in windows Jul 18, 2025 am 04:05 AM

TosetJAVA_HOMEonWindows,firstlocatetheJDKinstallationpath(e.g.,C:\ProgramFiles\Java\jdk-17),thencreateasystemenvironmentvariablenamedJAVA_HOMEwiththatpath.Next,updatethePATHvariablebyadding%JAVA\_HOME%\bin,andverifythesetupusingjava-versionandjavac-v

Java Microservices Service Mesh Integration Java Microservices Service Mesh Integration Jul 21, 2025 am 03:16 AM

ServiceMesh is an inevitable choice for the evolution of Java microservice architecture, and its core lies in decoupling network logic and business code. 1. ServiceMesh handles load balancing, fuse, monitoring and other functions through Sidecar agents to focus on business; 2. Istio Envoy is suitable for medium and large projects, and Linkerd is lighter and suitable for small-scale trials; 3. Java microservices should close Feign, Ribbon and other components and hand them over to Istiod for discovery and communication; 4. Ensure automatic injection of Sidecar during deployment, pay attention to traffic rules configuration, protocol compatibility, and log tracking system construction, and adopt incremental migration and pre-control monitoring planning.

Implement a linked list in Java Implement a linked list in Java Jul 20, 2025 am 03:31 AM

The key to implementing a linked list is to define node classes and implement basic operations. ①First create the Node class, including data and references to the next node; ② Then create the LinkedList class, implementing the insertion, deletion and printing functions; ③ Append method is used to add nodes at the tail; ④ printList method is used to output the content of the linked list; ⑤ deleteWithValue method is used to delete nodes with specified values and handle different situations of the head node and the intermediate node.

Advanced Java Collection Framework Optimizations Advanced Java Collection Framework Optimizations Jul 20, 2025 am 03:48 AM

To improve the performance of Java collection framework, we can optimize from the following four points: 1. Choose the appropriate type according to the scenario, such as frequent random access to ArrayList, quick search to HashSet, and concurrentHashMap for concurrent environments; 2. Set capacity and load factors reasonably during initialization to reduce capacity expansion overhead, but avoid memory waste; 3. Use immutable sets (such as List.of()) to improve security and performance, suitable for constant or read-only data; 4. Prevent memory leaks, and use weak references or professional cache libraries to manage long-term survival sets. These details significantly affect program stability and efficiency.

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Building RESTful APIs in Java with Jakarta EE Building RESTful APIs in Java with Jakarta EE Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

See all articles