search
HomeJavajavaTutorialGraphical introduction to the differences between String, StringBuffer and StringBuilder and stack memory allocation in Java

The String class in Java is a very commonly used class, but the least attention is paid to its details, so most interviews will focus on this class. For example, String str = new String("hello"); opens up several memory spaces, the difference between String and StringBuffer, etc. Here is my understanding:

String is a class modified by final and cannot be inherited. StringBuffer is also a class modified by final.

1. JVM memory division

There are mainly 4 pieces of memory in java. These memory spaces are: stack memory space, heap memory space, global data area, and global code area

1. Stack memory space: Save all object names (the address of the referenced heap memory space is saved)

2. Heap memory space: Save the specific content of each object

3. Global data area: Save static type data attributes (global data)

4. Global code area: Save all method definitions


In the JVM, heap memory is the memory space that stores the content of object instantiation (program data). Stack memory stores the name of the object, and its content points to the address of the corresponding heap.

It can also be said that: all object names are stored in stack memory, and the specific contents of the objects are maintained in heap memory. Reference type data must use the new keyword to open up space in heap memory.

2. Memory allocation of Sring

String has a special feature: when constructing a String object, you can use new construction or "hello" direct construction. Of the two methods, it is recommended to use the second one.

1. String a = "hello";

2. String a= new String("hello");

The explanation is as follows:

1: An object reference a is defined in the stack memory, pointing to the memory address of the value "hello" in the heap memory. Finally a memory space was opened up

2: An object reference of a is redefined in the stack memory, first pointing to the memory address of the heap memory with the value "hello", and then pointing to the address of the heap memory with the value of "hello" after new. In the end, two spaces were opened up. The first space has no object references and will be garbage collected by the JVM.

The diagram is as follows:

It is not difficult to understand the following codes after understanding the above:

 
package andy.string.test;  
  
/**   
 * @author Zhang,Tianyou   
 * version:2014-11-25 下午4:15:14   
 *  
 *   
 */  
  
public class TestString {  
  
    public static void main(String[] args){  
        String a = "hello";  
        String b = "hello";  
        String c = new String("hello");  
        String d = new String();  
        d = "hello";  
        String e = c;  
          
        System.out.println("a==b ? " + (a== b));  
        System.out.println("a==c ? " + (c== b));  
        System.out.println("a==d ? " + (a== d));  
        System.out.println("a==e ? " + (a== e));  
        System.out.println("c==d ? " + (c== d));  
        System.out.println("c==e ? " + (c== e));  
    }  
}



##Among them only a==b==d and c=e.


Explanation:


1. String does not want to wait for the heap memory every time it is new, and d does not want to wait after new allocates a new address. , and abandon the address after new to point to the memory address corresponding to a, so they are the same.

2. The heap memory space pointed to by the direct assignment method of "hello" assignment is the same. String uses a shared design in Java. It forms an object pool in Java. This object pool can save multiple objects. If the newly instantiated object already exists in the object pool, it will not be repeatedly defined and used directly from the object pool. . So


for existing content, the object will point to the space address of the already instanced instance.

3. e points directly to the memory space of C.

4. Therefore, when using String, it is recommended to use direct assignment to reduce memory space and improve performance.


3. The difference between String, StringBuffer and StringBuilder

1. String, StringBuffer and StringBuilder are all modified by final and cannot be inherited and rewritten. of.

2. After String is instantiated, the content size of its memory space cannot be modified; StringBuffer is a thread-safe variable character sequence that can be dynamically modified in the heap memory after instantiation. content, so the memory length and size are variable; after StringBuilder is instantiated, the memory size and length are also variable, no

The difference is that StringBuilder is not thread synchronized, so its operation must be more efficient than StringBuffer.

This is what some people will think:

             String str = "hello"; Hasn’t it also changed?

In fact, the above code has opened up 3 spaces in the memory, namely: "hello", "andy", "helloandy". Their heap memory size is fixed, and finally str points to "helloandy" the heap address. As shown in the figure below:

## and StringBuffer will only open a memory space, you can use APEND to add delete and other operation content.

String Every time an object is generated, it will have an impact on system performance. Especially when there are too many unreferenced objects in the memory, the JVM's GC will start to work, and the speed will definitely be quite slow. But if you use the StringBuffer/StringBuilder class, the result will be different. Each time the result will be an operation on the StringBuffer/StringBuilder object itself, instead of generating a new object and then changing the object reference.

Therefore, when cyclically assigning values ​​to a string, it is best to use StringBuffer (thread-safe) or StringBuilder, which can save memory and improve performance. Remember

. ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​


Statement
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
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 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 to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

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...

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...

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 set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

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