Java String pool - how strings are stored on the heap

Consider the following code:

String s1 = "Hello world"
String s2 = "Hello world XXX"

I assume these strings are stored in the same line of a Java String:

  • Hello World
  • Hello world XXX

How are these rows stored in the memory of the row pool that is on the heap? Are stored in a special heap for the row pool? Is there any string index for SP or are these strings stored in an ordered collection? What happens if "Hello world AAA" is added to the SP? Thank.

+4
source share
2 answers

Lines are immutable. For your example, there will be two objects in String Pool. If you are interested in creating, here is a very good post with a simple explanation: http://www.journaldev.com/797/what-is-java-string-pool .

:

String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Hello WorldXXX";

2 , Hello World, s1 == s2; true ( ), Hello WorldXXX .

, decsription wiki.

: , new, ( String Pool). , , String Pool, , String, ( String Pool).

https://en.wikipedia.org/wiki/Flyweight_pattern;)

0

, , Java Virtual Machine ( ):

String s1 = "Hello world";
String s2 = "Hello world XXX";

:

String s3 = new String("Hello world");
String s4  = new String("Hello world XXX");

JVM . , , ( , : s1 == s2 true). , String Java , hashcode , .

new JVM . , s1 == s3 false. : String.equals(), , .

0

Source: https://habr.com/ru/post/1665876/


All Articles