What is the Java string pool and what is the difference between "s" and "new String" (the "s")

Asked 2 years ago, Updated 2 years ago, 42 views

What does String Pool mean? And what is the difference between the two declarations below:

String s = "hello";
String s = new String("hello");

Is there a difference that JVM stores two strings?

java string

2022-09-22 13:09

1 Answers

String pool is an implementation of the concept of string interning by JVM.

Computer-engineered string interning is a method that stores only one copy of each unique string value (which does not necessarily change). Interning strings increases time and space efficiency in time-consuming tasks, such as creating or interning strings. The unique value of the String is stored in the string inside pool.

Basically, the string inside pool allows runtime to save memory by keeping the unchanged string in the pool. So instead of creating multiple instances in the application area, it allows you to reuse instances of strings that already exist.

To add something interesting, interning the string is a good example of a flyweight design pattern:

Flyweight is a software design pattern. Flyweight is an object and minimizes memory usage by sharing as much data as possible with other similar objects. It is a simple way to use a large amount of objects when repeated operations exceed memory usage.


2022-09-22 13:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.