Special string Types in Java

Source: Internet
Author: User
Tags constant stringbuffer

String in Java is a special wrapper class data that has two forms of creation:
    1. String s = "abc";
    2. string s = new String ("abc");
    first creates an object reference variable s in the stack for the string class, and then goes to find out if "abc" is stored in the string constant pool, and if not, creates three char-type values ' A ', ' B ', ' C ' in the stack, A string object is then created in the heap, whose value is the array {' A ', ' B ', ' C '}, which consists of the three char values created in the stack, and then this string object is stored in the string constant pool, and then the S is pointed to the address of the object, if " ABC "has been saved in the string constant pool, the object with the value" ABC "is found in the string constant pool, and the S is pointed to the address of the object.     first Feature: The JVM will automatically determine if it is necessary to create a new object based on the actual data in the stack.     the second type can be decomposed into two steps 1, String object = "abc"; 2, String s = new String (object); The first step is to refer to the first method of creation, and the second step because "ABC" has been created and saved to the string constant pool, so the JVM will only create a new string object in the heap whose value shares the three char values already in the stack.     second feature: Create new objects in the heap, regardless of whether their string values are equal, whether it is necessary to create a new object.     before you can tell a string comparison, you must understand the difference between = = and equals: Because all Java classes inherit from the object base class, and equals is implemented with = = in object, so equals and = = are the same, Are comparison object addresses, most of the classes in the Java API rewrite the Equals method, including the wrapper class for the base data type, the string class, and so on. For the string class = = To compare the addresses of two string objects, equals is used to compare the contents (values) of two string objects.     Example 1: string constant pool use string s0 = "abc"; String S1 = "abc"; System.out.println (S0==S1);  True to see that S0 and S1 are pointing to the same object. Example 2:string the difference between = = and equals  string s0 =new String ("abc"); String S1 =new string ("abc"); System.Out.println (S0==S1); False shows that the new method is to generate different objects System.out.println (s0.equals (S1)); True to see that equals compares the contents of two string objects (values)     Example 3: Compile period determines string s0= "HelloWorld"; String s1= "HelloWorld"; String s2= "Hello" + "word"; System.out.println (S0==S1); True to see that S0 and S1 are the same object System.out.println (S0==S2); True to see that s0 and S2 are the same object     parse: Because the "HelloWorld" in the example S0 and S1 are string constants, they are determined at compile time, so s0==s1 is true; "World" is also a string constant, and when a string is concatenated by multiple string constants, it is certainly a string constant, so S2 is also parsed as a string constant at compile time, so S2 is also a reference to "HelloWorld" in the constant pool. So we come to s0==s1==s2;       Example 4: Compile time can not be determined  string s0= "HelloWorld"; String S1=new string ("HelloWorld"); String s2= "Hello" + new String ("World"); System.out.println (S0==S1); False System.out.println (S0==S2); False System.out.println (S1==S2); false    Analysis: Strings created with new string () are not constants and cannot be determined at compile time, so the strings created by new string () are not placed in the constant pool, they have their own address space. S0 is also a reference to "HelloWorld" in the constant pool, s1 because it cannot be determined at compile time, so it is a reference to the new object "HelloWorld" created at run time, S2 because there is a second part new String ("World") so there is noThe method is determined at compile time, so it is also a reference to the newly created object "HelloWorld";      Example 5: Compile-time optimization string s0 = "A1"; String S1 = "a" + 1; System.out.println ((S0 = = S1)); result = true String s2 = "Atrue"; String s3= "a" + "true"; System.out.println ((s2 = = s3)); result = True String S4 = "a3.4"; String S5 = "a" + 3.4; System.out.println ((A = = b)); result = true    Analysis: During the program compile time, the JVM optimizes the "+" connection of the constant string to the concatenated value, and with "a" + 1, the compiler optimizes it to be A1 in class. The value of its string constants is determined at compile time, so the final result of the above program is true.     Example 6: Compile period can not be determined  string S0 = "AB"; String S1 = "B"; String s2 = "a" + S1; System.out.println ((S0 = = s2)); result = false    Analysis: The JVM has a string reference, because there is a string reference in the string's "+" connection, and the referenced value cannot be determined during the program compile time, i.e. "a" + S1 cannot be optimized by the compiler. Only during the program run time to dynamically allocate and assign the new address after the connection to S2. So the result of the above program is also false.     Example 7: Compile period determine  string s0 = "AB"; Final String S1 = "B"; String s2 = "a" + S1; System.out.println ((S0 = = s2)); result = true    Analysis: The only difference between [6] is that the S1 string has a final decoration, and for a final modified variable, it is parsed at compile time to a local copy of the constant value stored to its own constant In the pool or embedded in its byte stream. So at this point the "a" + S1 andThe "a" + "B" effect is the same. Therefore, the result of the above program is true.     Example 8: Compile time cannot determine string s0 = "AB"; Final String S1 = getS1 (); String s2 = "a" + S1; System.out.println ((S0 = = s2)); result = False private static String getS1 () {return "B";}     Analysis: The JVM for the string reference S1, its value in the compilation period can not be determined, only after the program run time call method, the return value of the method and "a" to dynamically connect and assign the address to S2, so the result of the above program is false.   about the immutable design of string:    string is a typical representation of immutable classes (note: Basic types of wrapper classes are immutable) and is a typical application of immutable design patterns. Once the string variable is initialized, it cannot be changed, and the state of the object is not changed, which increases the robustness of the shared object, reduces the error of object access, and avoids the need to synchronize during multi-threaded sharing. The implementation of     immutable mode mainly has the following two points:    1. In addition to constructors, there should be no other function (at least any public function) to modify any member variable.     2. Any function that makes a member variable get a new value should keep the new value in the new object, leaving the original object unmodified.     the non-variability of string causes the cost of using the + sign for the strings variable:    example 9:string s = "a" + "B" + "C"; String S1 = "a"; String s2 = "B"; String s3 = "C"; String S4 = S1 + s2 + s3;     Analysis: the creation of the variable s is equivalent to string s = "abc"; The compiler is optimized by the example above, where only one object is created. As can be known from the above example, S4 cannot be optimized at compile time, its object creation is equivalent to:    stringbuffer temp = new StrinGbuffer ();    temp.append (S1). Append (S2). Append (S3);    String s = temp.tostring ();     by the above analysis, it is not difficult to infer that the String uses the join operator (+) inefficiency reason analysis, like this code: public class Test {public static void main (String  Args[]) {String s = null; for (int i = 0; i <; i++) {s + = "a";}}} Every time you do it, you produce a StringBuffer object and then throw it away after append. The next time the loop arrives, it re-generates the StringBuffer object and then append the string so that it loops until the end. If we use the StringBuffer object directly for Append, we can save N-1 time to create and destroy objects. So for applications that want to concatenate strings in a loop, the StringBuffer or Stringbulider objects are generally used for append operations.  

Special String type in Java

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.