In Java programs often encounter a string similar to "Hello", then this type of string is how to store in Java, the following discussion of how the string constants in memory storage
At compile time, Java programs put constants (including Char, Byte, short, int, long, Boolean, and string types) that appear in the program into a place called a constant pool. Chang, also known as the object pool, is the name of the object that is stored in a constant pool.
What does the compiler do after a constant string such as "Hello" is detected in the source program:
First, create a string object in the constant pool that has the memory distribution of the object, such as:
Here you need to mention the two variables defined by the string:
Private final char value[]; The value is used for character storage
private int hash; Cache the hash code for the string
The first is an array of strings that are actually stored, and all of the strings are ultimately stored as character arrays. It is clear from this that the actual character array is stored in the heap, and a string object is stored in the constant pool.
When string str = "Hello" is executed, only the address of the "Hello" object in the constant pool is assigned to Str.
In addition to the memory model for the string constants above, there are several common constructors for the string class, and you need to be familiar with the memory model:
1. Public String () {
This.value = "". Value;
}
This is the default constructor, which assigns an empty string of character array references to the array reference of this class, so nothing in this string object is of course doing so without any benefit, Because a string object is created, it cannot change its contents (as can be seen from the Cosmetic keyword final of value).
2. public string (string original) {
This.value = Original.value;
This.hash = Original.value;
}
This simply duplicates the referenced values and does not copy the referenced content, which still points to the same object.
3. Public String (char value[]) {
This.value = arrays.copyof (value, value.length);
}。
Array.copyof () will re-copy the values in value, so the value in the This.value and parameter is exactly two objects, except that their values are the same.
The rest of the constructors are basically similar, and you can analyze them yourself
Java character constants Detailed