Java Programming Ideas-strings

Source: Internet
Author: User

1. Non-volatile

After initialization of the string class is immutable (immutable), first of all, I propose to look at the source code implementation of the String class, which is essentially the starting point to understand the string class. From here you can see:

1. The string class is final and cannot be inherited. Public final class String. 2, the String class is the essence of the character array char[], and its value cannot be changed. Private final char value[]; then open the API document of the string class, you can see: 3, the String class object has a special way to create, that is, directly specify such as String x = "abc", "ABC" represents a String object. X is the address of the "ABC" object, also called a reference to the "ABC" object. 4. String objects can be concatenated by "+". A new string is generated after concatenation. It can also be concatenated by concat (), which is explained later. 6. The Java runtime maintains a string pool, Javadoc translation is very vague "string buffer". The string pool is used to hold the various strings produced in the runtime, and the contents of the strings in the pool are not duplicated. The normal object does not exist in this buffer pool, and the object created only exists in the stack area of the method.  string object creation is also very fastidious, the key is to understand its principle. Principle 1: When using any way to create a string object s, the Java runtime (the running JVM) will hold this x in the string pool to find if there is a string object of the same content, if not, create a string s in the pool, otherwise, not add in the pool.   principle 2:java, whenever you use the New keyword to create an object, you will have to create a new object (in the heap or stack area).   Principle 3: Creating a String object using direct or string concatenation only checks the string in the maintenance string pool without creating one in the pool. However, the string object will never be created in the stack area again.   Principle 4: Creating a String object with an expression that contains a variable will not only examine the maintenance of the string pool, but also create a string object in the stack area.   In addition, the Intern () method of string is a local method, defined as public native String intern (); The value of the Intern () method is to allow the developer to focus on the string pool. When the Intern method is called, if the pool already contains a string equal to this string object (which is determined by the Equals (object) method), the string in the pool is returned. Otherwise, this string object is added to the pool, and a reference to this string object is returned. Let's look at an example:
public class Stringtest {public     static void main (string args[]) {         //Create string Object "ABC" in Pool and heap, S1 point to object         in heap string S1 = new String ("abc");         S2 points directly to the pool object "ABC"         String s2 = "abc";         A new "ABC" object is created in the heap, S3 points to the object         string s3 = new String ("abc");         The object "AB" and "C" are created in the pool, and S4 points to the pool object "ABC"         String s4 = "AB" + "C";         C points to the pool object "C"         String c = "C";         A new object "ABC" is created in the heap, and S5 points to the object         String s5 = "AB" + C;         String s6 = "AB". Concat ("C");         String s7 = "AB". Concat (c);         System.out.println ("------------Real string-----------");         System.out.println (S1 = = s2); False         System.out.println (S1 = = S3);//false         System.out.println (s2 = s3);//false         SYSTEM.OUT.PRINTLN (s2 = = S4); True         System.out.println (s2 = = S5);//false         System.out.println (s2 = s6);//false         System.out.println (S2 = = s7); False     }}
2. Using string does not necessarily create objects

When executing a statement that contains a string in double quotation marks, such as string a = "123", the JVM will first look in the constant pool and, if any, return a reference to the instance in the constant pool, otherwise create a new instance and place it into the constant pool. If String a = "123" + B (assuming B is "456"), the first half of "123" is the path of the constant pool, but the + operator is actually converted to [Sringbuffer]. Appad (), so eventually a gets a new instance reference, and A's value holds the address of a newly requested character array memory space ("123456"), while "123456" is not necessarily present in the constant pool.

Note: When defining a class using a format such as String str = "ABC", we always want to assume, of course, that the object of the string class was created by Str. worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. only through the new () method can you guarantee that a new object is created each time

3. Use new String to create an object

When executing string a = new string ("123"), first take the path of the constant pool to a reference to an instance, then create a new String instance on the heap, take the following constructor to assign a value to the Value property, and assign the instance reference to a

4.string.intern ()

After an instance of the string object calls the Intern method, you can have the JVM check the constant pool, and if there is no string sequence for the instance's Value property, such as "123" (note that the string sequence is checked instead of the instance itself), the instance is put into a constant pool. If there is a string sequence "123" that corresponds to the Value property of the current instance that exists in the constant pool, the reference to the instance of "123" in the constant pool is returned instead of the current instance's reference, even if the current instance's value is also "123".

  

public static void Main (string[] args) {        String s0 = "Kvill";         string S1 = new String ("Kvill");         String s2 = new String ("Kvill");         System.out.println (S0 = = S1); False        System.out.println ("**********");         S1.intern (); Although S1.intern () is executed, its return value is not assigned to s1        s2 = S2.intern ();//Assign a reference to "Kvill" in the constant pool to S2         System.out.println (S0 = = S1); Flase        System.out.println (S0 = = S1.intern ()),//true//description S1.intern () returns a reference to "Kvill" in a constant pool        System.out.println ( S0 = = s2); True    }
5.the difference between String,stringbuffer and StringBuilder

string constant, string length is immutable. String in Java is immutable (immutable).

StringBuffer: String variable (Synchronized, thread safe). If you want to modify the string content frequently, it is best to use stringbuffer for efficiency reasons, and if you want to turn to string type, you can call the ToString () method of StringBuffer.

StringBuilder: String variable (non-thread safe). Internally, the StringBuilder object is treated as a variable-length array that contains a sequence of characters.

6 Usage Policies

(1) Basic principles: If you want to manipulate a small amount of data, using string, single-threaded operation of large amounts of data, with StringBuilder, multi-threaded operation of a large number of data, with StringBuffer.

(2) Do not use the String class "+" for frequent splicing , because that performance is very poor, should use the StringBuffer or StringBuilder class, which is a more important principle in Java optimization.

(3) In order to achieve better performance, you should specify their capacity whenever possible when constructing stirngbuffer or Stirngbuilder. Of course, if you manipulate a string length (length) of no more than 16 characters, it is not necessary to construct an object with a capacity of 16 by default when no capacity is specified (capacity). Not specifying capacity can significantly degrade performance.

(4) StringBuilder is generally used inside the method to complete a similar "+" function, because the thread is unsafe, so after use can be discarded. StringBuffer are mainly used in global variables.

(5) In the same case, using stirngbuilder compared to using StringBuffer can only obtain the performance improvement of around 10%~15%, but the risk of multi-threading insecurity. In real-world modular programming, a programmer in charge of a module does not necessarily have a clear sense of whether the module will run in a multithreaded environment, so unless the system bottleneck is determined to be on the StringBuffer, and it is determined that your module will not run in multithreaded mode, can use StringBuilder, or use StringBuffer.

Java Programming Ideas-strings

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.