Related translations for string constants

Source: Internet
Author: User
Tags first string

I think the key to understanding this problem is to understand the relationship between a string object and its content, which is a private member of a string object, a char array (which holds the encoding of the string, which is the ' value ' member in the String class with the type char[]). The string class is a simple encapsulation that wraps a char array and provides some limited methods to modify the array while maintaining the invariance of the array (that is, not modifying the array itself, but creating a new object for the modification), The string object also remembers which part of the array is actually being used (see below). All this means that you can have two different string objects (quite lightweight) to point to the same char array. (PS: Personal annotations, except for the basic type, other types are stored references and arrays are the same, so the char array within a string object is actually a reference to a char array within a string object.)

I'll show you a few examples, as well as the hashcode () of each string object and the Hashcode () of their internal char array, and then I'll post the output of the java-c-verbose and the constant pool of the test class I provided. Please do not confuse the constant pool with the literal pool, which is somewhat different.

Advance Preparation

To achieve our testing purposes, I created a practical way to unpack the string object wrapper:

rivate int Showinternalchararrayhashcode (String s) {
    final Field value = String.class.getDeclaredField ("value");
    Value.setaccessible (true);
    return Value.get (s). Hashcode ();

This method will print out the hashcode of the char array, effectively helping us to understand whether a particular string is pointing to the same char array. Please don't worry, be patient and look down.

two literal literals exist in the same class

String one = "abc";
String two = "abc";
Incidentally, if you simply write "AB" + "C", the Java compiler will concatenate at compile time and the resulting code will be the same as the one above, of course this is only equivalent if the compiler knows all of your strings. (PS: A personal annotation, such as "a" + variable B + "C" in which there is an indeterminate variable B, is not automatically concatenated together)

class constant Pool Each class file has its own constant pool, which maintains a collection of constants that appear multiple times in code.    It contains frequently occurring strings, values, method names, and other content. The constant pool content for the example code above is posted here:

Const #2 = String   #38;  ABC
//...
Const #38 = Asciz   abc;
It is important to note the difference between string constant objects (#38) and string-pointing Unicode encoded text "ABC".
byte code
Here is the generated byte code. Note that one and two references are assigned the same, and point to the "ABC" string:
LDC #2; String ABC
astore_1    //one
LDC #2;//string ABC
astore_2    //two

Output
I use the following printout for each test statement:
System.out.println (Showinternalchararrayhashcode (one));
System.out.println (Showinternalchararrayhashcode (two));
System.out.println (System.identityhashcode (one));
System.out.println (System.identityhashcode (two));

No surprises have occurred, and the two pairs of outputs are equal:
23583040
23583040
8918249
8918249

This means that not only are each object pointing to the same char array, they are equal, but also that the variable one and two are two identical references, so the result of a = two is bound to be true, and obviously if the variable one and the variable two point to the same string object, Then One.value and Two.value are bound to be equal.
literal and new String ()
Now this example will be adjusted to what we want to see--a normal literal and a new String will use the same literal amount, and how it will work.
String one = "abc";
String two = new String ("abc");
In fact, this "ABC" literal is used in the source code two times, which will give you a hint.
class constant PoolIt's no different from the top.
byte code
LDC #2; String ABC
astore_1    //one

new #3;//class java/lang/string
dup ldc
#2;//string ABC
Invokespecial   #4;//method java/lang/string. " <init> ":(ljava/lang/string) V
astore_2    //two
It's important to note here that the first object was created just like the one that was previously shown, and there is nothing different, it simply gets a constant reference to the string (#2) that has been created in the constant pool. However, the creation of the second object is done through a regular constructor. But. The first string object passes as a parameter to the constructor of the second object, which you can understand:
String two = new string (one);
OutputThe output was somewhat surprising, and the second pair of references to the string object was understandable-because we created two string objects, and a string object was created for us in the constant pool (PS: personal annotations, which I understand as the so-called running constant pool, is to place some of the objects in a constant pool, such as a string literal, into a string object that is held by the virtual machine and assigned to the place it is used in code when the code needs the constant string. The second string object is created by hand. But why, but why the first pair of outputs indicates that these two string objects point to the same char [] array ...
41771
41771
8388097
16585653
However, when you look at the source code of a string constructor, you will not have a cold (very easy to understand):
public string (string original) {
    this.offset = Original.offset;
    This.count = Original.count;
    This.value = Original.value;
}
Did you see it? When you create a new string object based on an existing string object, the char array will be reused, the string object will not change, and no memory will be copied at all without involving a change to a string object, simply pointing to the reference.
run-time Modifications and intern ()
Next look at what happens when you change:
String one = "abc";
String two = "? abc". SUBSTRING (1);  Also two = "abc"
In fact, the Java compiler is not smart enough, so it will not be compiled during the second sentence value, so you will see the following:
class constant Pool  We saw two constant string references leading to two different literal constants:
Const #2 = String   #44;  ABC
Const #3 = String   #45;  ? ABC
Const #44 = Asciz   abc;
Const #45 = Asciz   abc;
byte code
LDC #2; String ABC
astore_1    //one

LDC #3;//string. ABC
iconst_1
invokevirtual   #4//method String.substring: (I) ljava/lang/string;
Astore_2    //two


The first string is the same as usual. The second string is created by "? ABC" and invokes substring (1).
Output
There's nothing special about it-we have two different strings, pointing to different char[] arrays:
27379847
7615385
8388097
16585653

Well, two char arrays are not different, the Equals () method still returns true. We now have two copies of the same string.
Now let's do one thing and run the following code:
two = Two.intern ();
After the execution, look at the hashcode. Not only did one and two point to the same char array, they are also the same references.
11108810
11108810
15184449
15184449
This means that one.equals (two) and one = = two pass the test. At the same time we save some memory space because the string "ABC" char array now has only one copy in memory (another will be reclaimed by the garbage collector because there is no reference)



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.