How does Java implement string concatenation?

I want to better understand the string pool. Please help me get to the source file of the class containing this Java implementation.

The question is more likely related to the search for source code or the implementation of a string pool, in order to better understand this concept, to learn more about some unknown or elusive things in it. So we can use strings even more efficiently or think of another way to implement our own garbage collectors if we have an application that creates so many literals and string objects.

+7
java
source share
2 answers

I'm sorry to disappoint you, but Java String-Pool is not a real Java class, but somewhere implemented in the JVM, that is, it is written as C ++ code. If you look at the source code of the String class (almost completely down), you will see that the intern() method is native. For more information you will have to go through the JVM code.

Edit: Some implementation can be found here ( C ++ header, C ++ implementation ). Find StringTable .

Edit2: As Holger pointed out in the comments, this is not a strict requirement for a JVM implementation. Thus, it is possible to have a JVM that implements a string pool in different ways, for example. using the actual Java class. Although all the widely used JVMs I know that I implement it in C ++ JVMs code.

+14
source share

You can read this article: Lines, Literally

When a .java file is compiled into a .class file, any string literals are marked in a special way, like all constants. When a class (note that loading occurs before initialization), the JVM goes through the code for the class and looks for string literals. When he finds one, he checks to see if the equivalent string is already referencing the heap. If not, it creates an instance of String on heaps and stores a reference to this object in the constant table. once a reference is made to this String object, any references to this String literal in your entire program is simply replaced by a reference to the object referenced by the string literal pool.

So, in the example shown above, there will be only one entry in the String Literal Pool, which will refer to a String object that contained the word "someString". Both local variables, one and two, will be assigned a reference to this single String object. You can see that this is true if you look at the output of the above program. Although the equals () method checks to see if String objects are being constructed that contain the same data ("someString"), the == operator, when they are used, checks for referential equality - this means that it will return true if and only if when two control variables refer to exactly the same object. In this case, the links are equal. From the above output you can see that the local variables, one and two, do not apply only to strings that contain the same data, they relate to the same object.

+4
source share

All Articles