A string is a type that we use frequently, and in fact sometimes it is thought that knocking the code is the repetition of the operation string, which is the characteristic of C in Java. The JDK nicely encapsulates the manipulation of strings. Three classes string, StringBuffer, StringBuilder. These three classes basically satisfy the need for us to use strings in different scenarios.
A, String
The JDK's explanation is "Strings is constant; Their valuescannot is changed after they is created "that is, once the string object is created is fixed, this is the advantage of being able to access between multiple threads, because only read and write.
Under normal circumstances we create a string object in the following two ways
STRINGSTR1 = "Liangcs";
STRINGSTR2 = new String ("Laingcs");
There is a difference between the two ways, which is related to the memory management of Java, which has been previously said to be immutable after string creation. So the string created in the first way is placed in the stack. More specifically, in a constant pool, the constant pool is used to hold the data that is determined in the compilation phase, and the basic data types such as the int we define are stored here.
A detailed process is that the compiler first checks the constant pool to see if there is a "string", assuming it is not created.
If there is, then direct the str1 point to that position.
Another way to create a string is through Newkeyword, or Java memory allocations, where Java places the new object in the heap, which is the object that is created at execution time. So every time we new, we create different objects, even if there's an identical one in the heap.
Write a sample sample
<span style= "FONT-SIZE:18PX;" >string str1 = "String"; String STR4 = "string"; String str2 = NewString ("string"); String str3 = NewString ("string"); /* Used to test two different ways of creating strings */system.out.println (str1 = = STR4); System.out.println (str2 = = STR3); System.out.println (STR3 = = str1); STR3 =str3.intern (); An uncommon method System.out.println (Str3 = = str1); This execution result is true// explanation: The contents of two strings are exactly the same, thus pointing to the same area in the constant pool false // Explanation: Each time new is created with an object false/ /Explanation: note = = The comparison is the address, not but the content true//Introduce the Intern method, this method will return a string in the constant pool of an address, Suppose a constant pool has the same string as the STR3 content to return that address. If not, a string is created in the constant pool and then returned. In fact, STR3 now points to the address of str1. </span>
The question that many people have is that since the string is constant, then why STR1 + "some" is legal, in fact. Each time a string is changed, a new object is created.
So if you need to change a string constantly, the efficiency is very low, because the advantages of the heap is able to dynamically add space, disadvantage is the allocation of new space consumption is very large. For example, let's look at the following test.
<span style= "FONT-SIZE:18PX;" > long Start =system.currenttimemillis (); for (int i = 0; i < 50000; i++) { str1+= ""; } Long end = System.currenttimemillis (); System.out.println ("The Run Timeis" + (End-start) + "MS");</span>
The execution result is that the run time is 3538 MS assumes that you add a few more 0 times more slowly after the number of cycles.
Because every time the loop is created, the object of the heart. So how does the JDK solve the problem?
Here's what we say.
Second, StringBuffer.
StringBuffer is a thread-safe, reliable guarantee of multithreaded access. The most important thing is that he is mutable, that is, we are going to manipulate a string that is often changed, and that we can use this class, the Main method is append (corresponding to the concat method of string) and the Insert method, and as for how to use it, there is not much to say. You can view the API yourself.
<span style= "FONT-SIZE:18PX;" > StringBuilder sb = new StringBuilder ("String Builder"); StringBuffer SF = newstringbuffer ("string buffer"); Long start =system.currenttimemillis (); for (int i = 0; i < 50000; i++) { //str1+= ""; Sb.append (""); } Long end = System.currenttimemillis (); System.out.println ("The Run Timeis" + (End-start) + "MS");</span>
Testing, this time only needs 8ms. This is efficiency.
Third, StringBuilder
So next, ask StringBuilder what it is. In fact this is what we try to use. This is the new class that was added after the JDK 1.5 version number. The front says that StringBuffer is thread-synchronized. So very many cases. We only use a thread, that synchronization is bound to bring about an efficiency problem, StringBuilder is the StringBuffer version number of non-thread synchronization, the method is almost the same. Just one thread safe (for multithreading) one is not thread safe (for single threaded).
In fact, look at the JDK source code will find that StringBuffer is in the various methods added keywordsyncronized
The StringBuilder is also a mutable string object. He differs from StringBuffer in that it is thread insecure and, based on this, it is generally faster than stringbuffer. As with StringBuffer, the main operation of Stringbuider is also the Append and insert methods.
Both of these methods effectively convert the given data to a string. The character of the string is then added to or inserted into the string generator.
A comparison of the three
A brief talk. The main performance difference between the string type and the StringBuffer type is actually that the string is an immutable object (why?). Ask the Java designer, why is String not a native type? Therefore, each time the string type is changed, it is actually equivalent to generating a new string object, and then pointing the pointer to the new string object, so the string that often changes the content is best not to use string, because each generation of the object will have an impact on the system performance, In particular, the JVM's GC starts to work when there are no more reference objects in memory. That speed is bound to be quite slow. Here is a sample that is not very appropriate:
<span style= "FONT-SIZE:18PX;" > String S1 = "abc"; for (int I = 0; I < 10000; i++) //For simulator multiple calls { s1+ = "def"; s1= "abc"; } </span>
Assuming this is the case, after the for loop is complete, assume that the in-memory object is not cleaned out by the GC. In memory, there are tens of thousands of them together. Staggering number, and assuming this is a system that is used by a very large number of people, this is not much. So you must be careful when you use it.
Assuming that the StringBuffer class is used, the result is different. Each result operates on the StringBuffer object itself, rather than generating a new object. Change the object reference again.
So under normal circumstances we recommend using StringBuffer, especially if the string object is often changed. In some special cases, string concatenation is actually interpreted by the JVM as a concatenation of StringBuffer objects, so the speed of a string object is not slower than the StringBuffer object, especially in the following string object generation. String efficiency is far faster than StringBuffer:
String S1 = "This was only a" + "simple" + "test";
StringBuffer Sb = Newstringbuilder ("This was only a"). Append ("simple"). Append ("test");
You will be surprised to find that the speed at which the String S1 object is generated is simply too fast, and that at this time the StringBuffer is not at all dominant at all. In fact, this is a JVM trick, in the JVM's eyes. This one
String S1 = "This was only a" + "simple" + "test"; The fact is:
String S1 = "This was only asimple test"; So of course it doesn't need too much time. But it is important to note that if your string is from another string object, the speed is not as fast. Such as:
String S2 = "This was only a";
String S3 = "simple";
String S4 = "Test";
String S1 = S2 +s3 + S4;
At this point the JVM will behave in the same way as it did. The S1 object is not built as fast as it was just now, and we can test it for a while.
From this we get the first step of conclusion:
In most cases StringBuffer >string
And what about StringBuilder with them? First of all, StringBuilder is a newly added class in JDK5.0. The difference between it and StringBuffer see the following introduction (source Javaworld):
Java.lang.StringBuffer A variable sequence of characters for thread safety. String buffer that resembles string. But cannot be changed. String buffers can be safely used with multiple threads.
Be able to synchronize these methods when necessary. As a result, all operations on a particular instance appear to occur in a serial order that is consistent with the sequence of method calls made by each thread involved.
Each string buffer has a certain amount of capacity.
Only the length of the character sequence included in the string buffer does not exceed this capacity, there is no need to allocate a new array of internal buffers.
Assume an internal buffer overflow. This capacity is actively increasing itself. Starting with JDK 5.0, an equivalence class for this class was added to a single thread. That is StringBuilder.
The StringBuilder class should usually be used preferentially compared to this class, because it supports all the same operations, but because it does not run synchronization. So the speed is faster.
However, it is not safe to assume that an instance of StringBuilder is used for multiple threads. If this synchronization is required, StringBuffer is recommended.
It is expected that everyone will be able to identify the difference between them. So here's a general derivation:
In most cases StringBuilder >stringbuffer
Therefore, according to the transitive theorem of this inequality: in most cases
StringBuilder > Stringbuffer> String
For a summary of the three uses:
1. Suppose you want to manipulate a small amount of data with String
2. operating a large amount of data under a single-threaded operation string buffer StringBuilder
3. Multi- threaded operation string buffer operation of a large number of data StringBuffer
Iv. frequent use of string operations
1, string comparison
Equals ()------Infer whether the content is the same.
CompareTo ()------Infer the size relationship of the string.
Comparetoignorecase (String int)------ignores uppercase and lowercase letters when compared.
= =------Infer Whether the content is the same as the address.
Equalsignorecase ()------Infer whether the content is the same in case of ignoring uppercase and lowercase.
Reagionmatches ()------Whether or not some of the contents of a string are equally comparable (see API for details).
2. String Lookup
charAt (int index)------Returns the characters at the index position of the specified indices starting at 0.
IndexOf (String str)------retrieves STR from the beginning of the string and returns the first occurrence of the position without a return-1.
IndexOf (String str,intfromindex),------retrieves STR from the first fromindex character of the string.
LastIndexOf (String str)------Find the last occurrence of the position.
LastIndexOf (string str,intfromindex)----finds the last occurrence from the Fromindex character of a string.
Starwith (string prefix,inttoffset)-----test whether the substring starting at the specified index starts with the specified prefix.
Starwith (string prefix)------Test Whether this string starts with the specified prefix.
EndsWith (string suffix)------Test Whether this string ends with the specified suffix.
3. String interception
public string subString (int beginindex)------Returns a new string that is a substring of this string.
The string returned by the public string subString (int beginindex,int endIndex)------is from beginindex start to endIndex-1.
4. String substitution
Public String replace (char OldChar. Char Newchar).
Public String replace (charsequence target,charsequence replacement)------Replace the original Etarget subsequence with the replacement sequence. Returns a new string.
public string ReplaceAll (string regex. String replacement)------match the string with a regular expression. Note that the first number of ReplaceAll is the normal form, I have suffered from the previous.
Through my own study, I feel the fact that the best data is the JDK API, to make good use of.
Quad: string manipulation of Java strings, StringBuffer, and StringBuilder