To sum up, string (Java)

Source: Internet
Author: User
Tags true true

Original: http://topic.csdn.net/u/20090519/18/7b8cf7ef-bc06-4d26-8a2c-692eb0562231_2.html

 

Author: zangxt

The string class is a very important class in Java. Here we will summarize the special features of this class. The following documents are translated from the Java language specifications (the third edition) and Java Virtual Machine specifications (the second edition), and some directly extract the original documents. The following code is compiled using sun jdk1.6 javac.

 

1. string literal, which is translated as a literal constant. It consists of 0 or more characters enclosed by double quotes, such as "ABC" and "Hello World. A string literal constant always references the same string instance. For example, the two constants "ABC" and "ABC" reference the same object.

 

Program test:

Package testpackage;

Class test {

Public static void main (string [] ARGs ){

String Hello = "hello", Lo = "Lo ";

System. Out. Print (Hello = "hello") + "");

System. Out. Print (other. Hello = Hello) + "");

System. Out. Print (other. Other. Hello = Hello) + "");

System. Out. Print (Hello = ("El" + "Lo") + "");

System. Out. Print (Hello = ("El" + LO) + "");

System. Out. println (Hello = ("El" + LO). Intern ());

}

}

 

Class other {static string Hello = "hello ";}

 

Another package:

 

Package Other;

Public class other {static string Hello = "hello ";}

Output:

True true false true

The conclusion is as follows:

1) in the same package, the same string literal constant in the same class indicates the reference to the same string object.

2) in the same package, the same string literal constants in different classes represent references to the same string object.

3) the same string literal constant in different classes under different packages also indicates the reference to the same string object.

4) The string calculated by using a constant expression is calculated during compilation and treated as a string literal constant.

5) for the string (non-constant expression) obtained through the connection operation, the connection operation is run and new objects are created, so they are different.

6) Call the intern operation for a calculated string explicitly. The result is a string literal constant with the same content.

Note:

1) string STR = "A" + "B" + "C" + "D ";

How many string objects will be generated when this statement is run? 1. Refer to the above 5th articles. The string obtained by using a constant expression is calculated during compilation. Therefore, only one "ABCD" String object exists when executing this sentence.

For definitions of constant expressions, see Java language specifications. Another example:

Final string str1 = "";

String str2 = str1 + "B ";

How many string objects will be generated when the second sentence is executed? 1. Because str1 is a constant, str1 + "B" is also a constant expression, which is calculated during compilation.

In this case, do not say that it depends on the specific compiler or virtual machine implementation, because this is part of the Specification. Generally, Java compiler implementation should comply with the Java language specification, while Java Virtual Machine implementation should comply with the Java Virtual Machine specification.

 

2) do not use strings like this:

String STR = new string ("ABC ");

Instructions in Reference documents:

String

Public String (string original)

Initialize a newly created String object to indicate a character sequence that is the same as the parameter. In other words, the newly created string is a copy of the parameter string. Because string is unchangeable, you do not need to use this constructor unless you need an explicit copy of original.

Parameters:

Original-a string.

Note: you do not need to use this constructor !!!

 

3) separately stated 6th points:

String STR = new string ("ABC ");

STR = Str. Intern ();

When the intern method is called, if the pool already contains a string equal to this string object (determined by the equals (object) method), the string reference in the pool is returned. Otherwise, this string object is added to the pool and a reference to this string object is returned.

Obviously, in this example, the object referenced by "ABC" is already in the string pool, and then intern is called to return the reference of the object whose content already exists in the pool is "ABC. This problem is also described in the above example.

2. An instance of the string class indicates the Unicode Character Sequence. A string literal constant is a reference to a string instance. (The literal constant is "Reference "!)

3. String Conversion

For the basic type, convert it to the reference type first. For the reference type, call the tostring () method to obtain the string. If the reference type is null, the converted string is "null ".

4. String link operation "+"

If the result of the "+" operation is not a constant during the compilation period, a new object is created implicitly. To improve performance, the specific implementation can adopt stringbuffer. The stringbuilder class connects multiple parts and converts them to strings, so as to avoid generating and discarding the intermediate String object. To achieve the purpose of sharing instances, constants during the compilation period are always "interned.

Example:

String A = "hello ";

String B = a + 1 + 2 + "world! ";

Disassembly result:

0: LDC #2; // string hello

2: astore_1

3: New #3; // class Java/lang/stringbuilder

6: DUP

7: invokespecial #4; // method Java/lang/stringbuilder. "<init>" :() V

10: aload_1

11: invokevirtual #5; // method Java/lang/stringbuilder. append :( ljava/lang/string;) ljava/lang/stringbuilder;

14: iconst_1

15: invokevirtual #6; // method Java/lang/stringbuilder. append :( I) ljava/lang/stringbuilder;

18: iconst_2

19: invokevirtual #6; // method Java/lang/stringbuilder. append :( I) ljava/lang/stringbuilder;

22: LDC #7; // string world!

24: invokevirtual #5; // method Java/lang/stringbuilder. append :( ljava/lang/string;) ljava/lang/stringbuilder;

27: invokevirtual #8; // method Java/lang/stringbuilder. tostring :() ljava/lang/string;

30: astore_2

 

Actually

String B = new stringbuilder (). append (a). append (1). append (2). append ("world"). tostring ();

Here, stringbuilder is used to avoid performance degradation caused by the generation of temporary string objects in the middle.

In addition, the following two examples mainly describe the compilation frequency:

1)

String c = "C ";

String STR = "A" + "B" + C;

And

2)

String c = "C ";

String STR = C + "A" + "B ";

1) In, STR = "A" + "B" + C; compiler analysis uses "A" + "B" as the compile time, generating the literal constant "AB ", so the actual execution of this sentence is linked to "AB" and C. Actually

String STR = new stringbuilder (). append ("AB"). append (c). tostring ();

2), string STR = C + "A" + "B ";

When the compiler analyzes C as a variable, the "A" + "B" in the future will not be used as the compile time.

The actual running time is equivalent to the execution

String STR = new stringbuilder (). append (c). append ("A"). append ("B"). tostring ();

5. Create a String object:

1) a class or interface that contains a string literal constant is a string object that is created at the time of loading. In either of the following cases, a New String object is not created.

A) An identical literal constant has already appeared.

B) An intern operation has been called for a string with the same content (for example, the intern operation is called for a string generated by the operation ).

2) The string Join Operation of a non-constant expression sometimes produces a String object that represents the result.

3) The string literal constant comes from the constant_string_info structure in the binary representation of the class or interface (that is, in the class file. The constant_string_info structure provides the Unicode Character Sequence that constitutes a string literal constant.

4) To generate a string literal constant, Java Virtual Machine checks the Character Sequence given by the constant_string_info structure:

A) if the string instance with the same character exchange content as the constant_string_info structure has called string. Intern, the resulting string literal constant comes from the same instance of the string.

B) Otherwise, create a new string instance based on the Character Sequence in constant_string_info and call the intern method.

Example: A scjp question

11. Public String makinstrings (){
12. String S = "Fred ";
13. S = S + "47 ";
14. S = S. substring (2, 5 );
15. S = S. touppercase ();
16. Return S. tostring ();
17 .}
How many string objects will be created when this method is invoked?

There are three answers. As described above, "Fred" and "47" are literal constants of strings created during class loading. Here is the question (!) How many string objects are created, and two literal constants are not included. Three are: "fred47", "ed4", and "ed4 ".

6. Comparison of string and basic types of packages

Similarities. They are all unchanged classes. When "=" is used, it may have similar properties.

After Java 5, Java added the function of automatic packing and unpacking. Therefore, it has the following nature:

Integer I = 5;

Integer J = 5;

System. Out. println (I = J );

Result: True.

This seems to be the same as string, but its implementation is extremely different. Here is a difference.

As we all know, automatic packing is implemented in this way:

Integer I = 5;

Equivalent

Integer I = integer. valueof (5); // note that it is not new INTEGER (5), which cannot meet the conventions in the Java language specification. For the conventions, see the final part of this article.

In integer, the static value is represented from-128 ~ An integer object of data between 127 and. Only the corresponding objects are returned if the number within this range is packed. Therefore

Integer I = 5;

Integer J = 5;

We get the same object. This is achieved through the design of the class library. String sharing is achieved through the direct support of Java virtual machines, which are essentially different.

This is part of the code in the integer class:

Private Static class integercache {

Private integercache (){}

Static final integer cache [] = new integer [-(-128) + 127 + 1];

Static {

For (INT I = 0; I <cache. length; I ++)

Cached [I] = new INTEGER (I-128 );

}

}

Public static integer valueof (int I ){

Final int offset = 128;

If (I> =-128 & I <= 127) {// must Cache

Return integercache. cache [I + offset];

}

Return new INTEGER (I );

}

For the basic type packing, the Java language specifications are described as follows:

If the boxed Variable P is true or false, the variable is in the/u0000 ~ The Byte/Char between/u007f, or a byte/Char between-128 ~ + Int/short between 127, so that R1 and R2 are the results of any two packing operations on P, then R1 = R2 is always true. Ideally, you should always get the same reference when packing a basic type variable. However, in practice, this is unrealistic under the existing technical conditions. The above rule is a pragmatic compromise.

Finally, we need to understand the passing parameter model when calling Java Methods: Java only has pass by value. (If this is not clear, there will be a mess of explanations. For example, typical Java involves both passing values and passing references. String is special ......)

// Change the parameter value?

Public void test (string Str ){

STR = "hello ";

}

// Change the parameter value?

Public void test (stringbuffer buffer ){

Buffer = new stringbuffer ("hello ");

}

// Exchange two integers?

Public void swap (integer a, integer B ){

Integer temp =;

A = B;

B = temp;

}

All three methods are meaningless.

Related Article

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.