[]java string-related knowledge in turn

Source: Internet
Author: User

Why strings are so important

Write for many years Java development should be not unfamiliar with the string, but I feel it more unfamiliar. Every learning of a programming language will have a lot to do with the word string. It seems to be really important.

A string is a series of strings of character combinations, and if written in C + + it should be understood that there are many functions and classes of operations on string operations that simplify the development of code. On the one hand, strings are frequently used in code, and on the other hand, the manipulation of strings is cumbersome.

At first I knew that the special treatment of string was in Delphi, because string was a key word in Delphi and was not the same as other basic types. A lot of relevant knowledge was learned at that time. The Java/.net also has a special handling of the string, which can be seen as important.

Because of the string in the program with a lot of, and the operation of a lot of this will bring memory consumption and performance problems, the need for special care, imagine a log system a day time to use how many string variables.

Learn about the string in Java

Java provides a string class support function, after all, the string is essentially a combination of a bunch of characters, then let's see what its characteristics.

    • Features of string

String is still stored in a char array, the operation of the data around it, but a bit special place, the code is as follows

private final char value[];

This char value[] can be found to be final, meaning that once a value is created it is immutable. This causes the string to be created every time a string has only one value, and the new value must be generated. Java uses the concept of a string constant pool for this processing. is to throw the string into a pool, if the same is the same. Of course, there is a premise, that is to use the following way

String s = "abc";

When you do this, the JVM is determined at compile time, and at run time it looks for "ABC" in the constant pool, does not add and returns, or returns the object of the constant pool. The advantage of this is that you do not need to create duplicate strings for the same string. But if you use the following code

String s1 = new String("abc");

This time the scene is changed, where the JVM creates an object S1 in the stack, but the value in S1 is also pointing to "ABC". You'll see the difference when you look at the string comparisons later.

    • A string comparison looks at a piece of code:
String s = "abc";String s1 = "abc";if (s == s1) { System.out.println("s == s1");}

Q: At this time s==s1?

The answer is equal, why? In fact, the JVM will go to the constant area when the S1 is created to find the string with the same value, and if so, return it to S1 so that S1 and S point to the same string, so it is equal.

But there is another situation that is not the same,

String s = "abc";String s3 = new String("abc");if (s == s3) {System.out.println("s == s3");}else { System.out.println("s != s3");}

This time it should print out s! = s3, because new is a string object that does create a fresh variable. So using the = = Comparison will naturally return false.

Compare it with equals?

String s = "abc";String s2 = new String("abc");if (s.equals(s2)) {System.out.println("s = s2");}else { System.out.println("s != s2");}

Printing is s = s2, because = = is used to compare two addresses, and equals is the value used to compare two variables. Take a look at the code of equals

PublicBoolean Equals (Object anobject) {if (this = = AnObject) {ReturnTrue }if (anobject instanceof String) { string anotherstring = (string) anobject; int n = value.length; if (n = = anotherString.value.length) {char v1[] = value; char v2[] = Anotherstring.value; int i = 0; while (n--! = 0) {if (v1[i]! = V2[i]) return false; i++;} return true;} return false;}        

In Equals, the first comparison is whether the address is the same, if it is not the same as value, because value is "ABC" Nature Returns True.

    • Intern method

There is a intern method in the string, we can try the following code first.

String s = "abc";String s3 = new String("abc");if (s.intern() == s3.intern()) {System.out.println("s.intern = s3.intern");}else { System.out.println("s.intern != s3.intern");}

Or the above S and S3, if the value returned using the respective intern method is compared, the output is S.intern = S3.intern. Looking for information. In conjunction with annotations, the Intern method actually returns the current string from the string constant pool, returns the current string if the current string already exists, and then returns the current string in a constant pool if the current string does not exist.

With this explanation it is clear that both S and S3 are returned by intern and are all "abc" in the constant pool, so the intern is equal when compared.

Meet StringBuffer and StringBuilder.
    • StringBuffer and StringBuilder which one is thread-safe?

The interview encountered this problem, I suddenly a little confused, did not pay much attention to these two classes, and the impression that there is only one stringbuffer in Java? Came back to look at the code originally StringBuffer is thread-safe, that is, the method of string manipulation has synchronized.

So open code Comment discovery is Jdk1.5 only started some StringBuilder, and in the later version added an unlocked class, it seems to solve the problem of non-concurrency scenario efficiency, no lock for the operation of large strings or performance improvement.

Well, yes, get a little knowledge.

Out of curiosity, I looked at the code for these two classes, which is somewhat similar to string, except that the chat[] is no longer final, which avoids the problem of generating a bunch of string objects when the string class is operating.

char[] value;
    • The role of StringBuffer and StringBuilder

Now that there's a string, what's the use of these two guys? In fact, the problem is still related to the principle of string. Because string is managed through a constant pool, this solves the problem of duplicate creation of the same string, but most of the strings are different, especially when doing string concatenation, if concatenation with string + creates a lot of string constants, which consumes performance and space.

To solve this problem, StringBuffer is used, essentially, through a variable sequence of characters, which does not require a new object to be generated when the string is manipulated, thus increasing memory usage.

Let's see how stringbuffer improves the stitching performance. View the code for Stringbuffer/stringbuilder (jdk1.5+) and discover that they all inherit from Abstractstringbuilder. Many of the code is actually done in Abstractstringbuilder. Because this problem is caused by splicing, here we mainly focus on the Append method.

public abstractstringbuilder Append ( String str) {if (STR = = null) return appendnull (); int len = str.length (); Ensurecapacityinternal (count + len); //determine capacity str.getchars (0, Len, value , count); //remove str characters into the value array count + = Len; Count cumulative return this;}       

The code is still quite clear, and the whole process is most important to write the value of STR to the current object by using the GetChars method of string. The GetChars method of string is as follows:

Publicvoidgetchars (int srcBegin, int srcend, char dst[], int dstBegin) {if (Srcbegin < 0) {throw new stringindexoutofboundsexception (Srcbegin); } if (Srcend > value.length) { Throw new stringindexoutofboundsexception (srcend);} if (Srcbegin > Srcend) {throw  New Stringindexoutofboundsexception (Srcend-srcbegin); } system.arraycopy (value, Srcbegin, DST, Dstbegin, srcend-srcbegin);}    

As you can see, a copy of the array is eventually made, because the value in Abstractstringbuilder is a variable char array, so the string operation only needs to be done on the char array. No new objects are generated like string, so nature becomes efficient.

Transferred from: http://www.cnblogs.com/5207/p/5892583.html

[]java string-related knowledge in turn

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.