Java Basics-Keyword-string

Source: Internet
Author: User
Tags java se

1 , the nature of string

Thread Safety 

Open string source code, class comments have such a paragraph of words "Strings is constant;" Their values cannot is changed after they is created. String buffers support mutable strings. Because String objects is immutable they can be shared. " This sentence summarizes one of the most important features of string: string is a constant of value immutable (immutable) and is thread-safe (can be shared).

Non-inheritable

The string class uses the final modifier, which indicates the second characteristic of the string class: The String class is not inheritable.

In Java, a class that is final decorated is not allowed to be inherited, and the member methods in the class default to the final method. In earlier versions of the JVM implementation, the final modified method was converted into inline invocation to improve execution efficiency. And starting with Java SE5/6, it's getting rid of this way. Therefore, in the current version of the Java SE, it is not necessary to consider using final to increase the efficiency of the method invocation. The method is set to final only if you are sure that you do not want the method to be overwritten.

The value is immutable, stored as a character array

Private Final Char value[]; Private Final int

From final modification, it can be seen that its immutability

Where the concat method of the string class is to be expanded, if the parameter length of the method equals 0 This returns this, otherwise it composes a new string, and immediately after the stitching parameter returns the new string

Let's look at the concat method of the String class. The first step in implementing this method is definitely to enlarge the capacity of the member variable value, and to redefine a large-capacity character array buf. The second step is to copy the characters from the original value into the BUF, and then copy the string value that needs to be concat to buf, so that buf contains the string value after concat. Here is the key to the problem, if value is not final, just let value point to buf, and then return this, it is done, there is no need to return a new string object. But... Pity... Since value is final, it cannot point to the newly defined mass array buf. "Return new string (0, Count + otherlen, buf);", which is the last statement of the string class Concat implementation method, which is returned with a new string object. That's the truth!

The string class actually holds strings through a char array.

Summary: String The essence is a character array, two features: 1 , the class cannot be inherited; 2 , non-denatured (immutable) .

 PublicString substring (intBeginindex,intEndIndex) {    if(Beginindex < 0) {        Throw Newstringindexoutofboundsexception (Beginindex); }    if(EndIndex >count) {        Throw Newstringindexoutofboundsexception (EndIndex); }    if(Beginindex >EndIndex) {        Throw NewStringindexoutofboundsexception (EndIndex-beginindex); }    return(Beginindex = = 0) && (endIndex = = count))? This :        NewString (offset + beginindex, EndIndex-beginindex, value); }   Publicstring concat (String str) {intOtherlen =str.length (); if(Otherlen = = 0) {        return  This; }    CharBuf[] =New Char[Count +Otherlen]; GetChars (0, Count, buf, 0); Str.getchars (0, Otherlen, buf, Count); return NewString (0, Count +Otherlen, BUF); }   PublicString Replace (CharOldChar,CharNewchar) {    if(OldChar! =Newchar) {        intLen =count; inti =-1; Char[] val = value;/*avoid GetField opcode*/        intOff = offset;/*avoid GetField opcode*/          while(++i <Len) {        if(Val[off + i] = =OldChar) {             Break; }        }        if(I <Len) {        CharBuf[] =New Char[Len];  for(intj = 0; J < I; J + +) {Buf[j]= val[off+J]; }         while(I <Len) {            Charc = Val[off +i]; Buf[i]= (c = = OldChar)?Newchar:c; I++; }        return NewString (0, Len, buf); }    }    return  This;

As can be seen from the three above methods, whether the sub, concat, or replace operations are not performed on the original string, a new string object is regenerated. This means that the most primitive string has not been changed after these operations.

"Any changes to the string object do not affect the original object, and any related change operations will generate a new object."

2. The memory mechanism of string

When the JVM runs, it divides the memory into two parts: heaps and stacks. The heap holds the objects that are created, while the stack holds local variables or references to the methods that call the procedure. When designing Java string Object memory implementations, a small amount of memory is created in the heap, called a constant pool of strings, dedicated to storing specific string objects.

There are two common ways to create Java String objects:

String reference variable name = "string Content"; String applies variable name =new string (< parameter sequence >);

Let's take a look at the first way to create a string object How memory is allocated, the code is as follows:

String s1= "Oseye.net"; String s2= "Oseye.net";

This describes the relationship of the referencing object, as well as the allocation of memory. The Java implementation steps are as follows:

    1. See if there is a string object with the same contents as "Oseye.net" in the string constant pool.
    2. If not, create a new string object that contains the content and point the reference variable to the object. For example, when you create a string s1, the string constant is not in the pool, a new object is created, and the reference S1 points to the object.
    3. If there is already a string object that contains the content, let the string reference point directly to the object. For example, when creating a string s2, the string constant pool already has an object containing that content, so the reference S2 directly points to the existing object.

Let's look at the second way of creating a String object:

String s1= "Oseye.net"; string S2=new string ("oseye.net");

This describes the relationship of the referencing object, as well as the allocation of memory. The Java implementation steps are as follows:

    1. You first create a string object that contains the specified content in the heap (not the constant pool) and point the string reference to the object. For example, in the preceding code, using new to create the string S3, it creates a string pair object with the content "oseye.net" directly in the heap and points the reference S3 to the object.
    2. Go to the string constant pool to see if there is an object that contains the content.
    3. If so, the new string object is associated with the same object in the string constant pool. For example, in this case, the object pointed to by S3 is associated with the S1 point.
    4. If not, then create a string object in the string constant pool that contains the content, and associate the objects in the heap with the newly created objects in the string constant pool.

We know that the new string object and the object in the string constant pool are connected and can be viewed by the Intern method, method signature:

 Public String Intern ()

This method references the specified string to the corresponding object in the string constant pool, and if it points to the object itself in the string constant pool, returns the object that it points to directly, or returns the object in the string constant pool to which the string reference is associated if it refers to the object in the heap. Examples are as follows:

 PackageNet.oseye; Public classExceptiontest { Public Static voidMain (string[] args) {String S1= "Oseye.net"; String S2=NewString ("Oseye.net"); if(s1==S2) {System.out.println ("String references S1 and string references S2 point to the same object"); }Else{System.out.println ("String references S1 and string references s2 not the same object"); }        if(S1.intern () = =S2.intern ()) {System.out.println ("String reference S1 and string reference S2 are associated with the same object in a string constant pool"); }Else{System.out.println ("String reference S1 and string reference S2 are not the same object in a string constant pool"); }    }}

Output Result:

String references S1 and string references S2 point to not the same object string reference S1 and string references s2 in the string constant pool are the same object

Java Basics-Keyword-string

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.