Deep understanding of String__java in Java

Source: Internet
Author: User

A, String class

To understand a class, the best way is to look at the implementation of this class source code, look at the string class Source:

Public final class String
    implements Java.io.Serializable, Comparable<string>, charsequence
{
    /** The value is used for character storage. *
    Private final char value[];

    /** the ' offset is ' the ' storage ' is used. * *
    private final int offset;

    /** The count is the number of characters in the String. *
    private final int count;

    /** Cache The hash code for the string */
    private int hash;//Default to 0

    /** use Serialversionuid from JDK 1.0 .2 for Interoperability * *
    private static final long serialversionuid = -6849794470754667710l;

    ........
}

From the above you can see several points:

1 The String class is the final class, meaning that the string class cannot be inherited, and that its member methods default to the final method. In Java, a class that is final decorated is not allowed to be inherited, and the member methods in that class default to the final method.

2 The above lists all the member properties in the String class, from which you can see that the string class actually holds the string through a char array.

Continue to see some method implementations of the string class below:

Public String substring (int beginindex, int endindex) {if (Beginindex < 0) {throw new Stringindexoutofbou
    Ndsexception (Beginindex);
    } if (Endindex > Count) {throw new stringindexoutofboundsexception (Endindex);
    } if (Beginindex > Endindex) {throw new stringindexoutofboundsexception (Endindex-beginindex); Return ((beginindex = 0) && (endindex = count)?
This:new String (offset + beginindex, endindex-beginindex, value);
    public string concat (string str) {int otherlen = Str.length ();
    if (Otherlen = = 0) {return this;
    } char buf[] = new Char[count + Otherlen];
    GetChars (0, Count, buf, 0);
    Str.getchars (0, Otherlen, buf, Count);
return new String (0, Count + otherlen, buf);
        Public String replace (char Oldchar, char Newchar) {if (Oldchar!= newchar) {int len = count;
        int i =-1; Char[] val = value; /* Avoid GetField opcode */intOff = offset;
        /* Avoid GetField opcode/while (++i < Len) {if (Val[off + i] = = Oldchar) {break;
        } if (I < len) {char buf[] = new Char[len];
        for (int j = 0; J < i; J +) {Buf[j] = val[off+j];
            while (I < Len) {char c = val[off + i]; Buf[i] = (c = = Oldchar)?
            NEWCHAR:C;
        i++;
        Return to New String (0, Len, buf);
} return this; }

As you can see from the three above methods, whether the sub, concat, or replace operations are not done on the original string, but a new string object is regenerated. That is, after these operations, the original string has not been changed.

Always remember here: "Once a string object is created, it is fixed, and any changes to the string object do not affect the original object, and any change operation associated with it will generate a new object."

Two, string constant pool

We know that the allocation of strings, like other object allocations, takes a lot of time and space, and we use very much of the string. JVM to improve performance and reduce memory overhead, some optimizations were made when instantiating strings: using string constant pools. Whenever we create a string constant, the JVM first checks the string constant pool and returns the instance reference in the constant pool directly if the string already exists in the constant pool. If the string does not exist in a constant pool, the string is instantiated and placed in a constant pool. Because of the immutability of string strings, we can be quite certain that there must be no two identical strings in the constant pool (this is critical to understanding above).

A constant pool in Java is actually divided into two forms: a static constant pool and a running regular pool.
The so-called static constant pool, that is, the constant pool in the *.class file, the constant pool in the class file contains not only string (number) literal, but also class, method information, occupy most of the class file space.
While running a regular pool, the JVM virtual machine loads the constant pool in the class file into memory after it completes the class mount operation, and is stored in the method area, which we often refer to as the constant pool of the method area.

Look at the following program:

String a = "Chenssy";
String B = "Chenssy";

A, B, and literally Chenssy are "chenssy" objects in the JVM string constant pool, pointing to the same object.

String c = new String ("Chenssy");

The new keyword must produce an object Chenssy (note that this chenssy differs from the chenssy above), and the object is stored in the heap. So there should be two objects on it: The C in the stack and the Chenssy in the Save heap. In Java, however, there are no two identical string objects at all. So the chenssy in the heap should be chenssy in the reference string constant pool. So the relationship between C, Chenssy, pool chenssy should be: c--->chenssy---> Pool chenssy. The whole relationship is as follows:

Through the above figure we can very clearly understand their relationship. So we modify the value in memory, and he changes it all.

Summary: Although a, B, C, and Chenssy are different objects, we can understand them from the internal structure of string. String c = new String ("Chenssy"), although the content of C is created in the heap, but his internal value refers to the value of the chenssy of the JVM constant pool, the parameter used to construct Chenssy is still a Chenssy string constant.

Let's look at a few more examples:

Example 1:

/**
 * Use the value of the literal way to assign
/public void Test1 () {
    String str1= "AAA";
    String str2= "AAA";
    System.out.println ("===========test1============");
    System.out.println (STR1==STR2);//true can see that str1 and str2 are pointing to the same object 
}

Executes the above code, and the result is: true.
Analysis: When the string str1= "AAA" is executed, the JVM first looks for the existence of the "AAA" object in the string pool, and if it does not, creates a "AAA" object in the string pool and returns the reference address of the "AAA" object in the pool to the string constant str1. This str1 points to the "AAA" string object in the pool, and if it does, does not create any objects, returning the address of the "AAA" object directly in the pool and assigning the string constant. When creating a String object str2, a "AAA" Object already exists in the string pool, returning the reference address of the object "AAA" directly to str2 so that str2 points to the "AAA" object in the pool, which means that str1 and str2 point to the same object. So the statement System.out.println (str1 = = str2) output: true.

Example 2:

/**
 * Create a new string object using the New keyword/public
void Test2 () {
    string Str3=new string ("AAA");
    String Str4=new string ("AAA");
    System.out.println ("===========test2============");
    System.out.println (STR3==STR4);//false can see that the way to use new is to generate different objects 
}

Executes the above code, and the result is: false.

Analysis: When you create a new string object with the New keyword, the JVM first looks for the "AAA" string object in the string pool and, if so, does not create a "AAA" object in the pool, creates a "AAA" string object directly in the heap, and then the "AAA" in the heap The address of the object is assigned to the reference STR3, in this way, STR3 points to the "AAA" string object created in the heap, and if not, first creates a "AAA" string object in the string pool, then creates a "AAA" string object in the heap, and then the heap of this "AAA" The address of the string object is assigned to the STR3 reference, so that str3 points to the "AAA" string object created in the heap. When a string Str4=new string ("AAA") is executed, when an object is created with the new keyword, each new object is given, which means that references Str3 and STR4 point to two different objects. So the statement System.out.println (STR3 = = STR4) Output: false.

Example 3:

/**
 * Compile-time determination *
/public void Test3 () {
    String s0= "HelloWorld";
    String s1= "HelloWorld"

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.