Collation of string-related knowledge in java and java string-related knowledge

Source: Internet
Author: User

Collation of string-related knowledge in java and java string-related knowledge
Why is string so important?

I have been writing java for many years and should be familiar with String, but I am more and more familiar with it. Every time you learn a programming language, you will have a lot of dealings with the keyword "string. It seems to be really important.

A string is a string of a series of character combinations. If you have written C/C ++, you should understand that there are many operation functions and classes in string operations, it is used to simplify code development. On the one hand, strings are frequently used in code, and on the other hand, string operations are very troublesome.

Initially I knew that the special treatment of String was in delphi, because String exists as a keyword in delphi, which is different from other basic types. At that time, I learned a lot about it. In java/. net, the string is also specially processed to show the importance.

This is because many strings are used in the program and there are also many operations, which will cause memory usage and performance problems. Special attention is needed, imagine how many string variables the system needs to use in a single day.

Let's take a look at the String in java.

Java provides the String class to support the String function. After all, the character String is essentially a combination of a bunch of characters. Let's take a look at its features.

  • Features of String

String stores the String in a char array. The data operations are centered around it, but the code is as follows:

private final char value[];

It can be found that the char value [] is added with final, that is, once the value is created, it cannot be changed. In this way, each time a String is created, only one value is generated, and a new value must be generated for the String operation. Java uses the String constant pool for this processing. It means to drop the string into a pool, and use the same string if they are the same. Of course, this also has a premise, that is, to use the following method

String s = "abc";

In this case, the jvm will be determined during the compilation period. During the runtime, it will first find whether "abc" exists in the constant pool, and add and return if no "abc" exists, if yes, return the object of the constant pool. The advantage of doing so is that the same string does not need to be created again. However, if the following code is used

String s1 = new String("abc");

The scenario changes at this time. Here, jvm will create an object s1 in the stack, but the value in s1 also points to "abc. The difference will be found later when we look at the string comparison.

  • The following code compares strings:
String s = "abc";String s1 = "abc";if (s == s1) {    System.out.println("s == s1");}

Q: Is s = s1?

The answer is equal. Why? In fact, the jvm will go to the constant area to check whether there are strings with the same value when s1 is created. If so, it returns to s1, so that s1 and s point to the same string, so it is equal.

But there is another case,

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

At this time, print s! = S3, because a new String object will indeed create a new variable. Therefore, if you use = for comparison, false is returned.

What if equals is used for comparison?

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

Print is s = s2, because = is used to compare two addresses, while equals is used to compare the values of two variables. Let's take a look at the equals code.

public boolean equals(Object anObject) {    if (this == anObject) {        return true;    }    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, first compare whether the address is the same, if not the same compare value, because the value is "abc", returns true.

  • Intern Method

There is an intern method in 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 by the intern method is compared, s. intern = s3.intern is output. After searching for information and comments, I learned that the intern method actually returns the current string from the String constant pool. If the current string already exists, the current string is returned. If the current string does not exist, put the current string into the constant pool and then return it.

With this explanation, we can understand that both s and s3 return "abc" in the constant pool through intern, so intern is equal.

Let's take a look at StringBuffer and StringBuilder.
  • Which of StringBuffer and StringBuilder is thread-safe?

I suddenly encountered this problem during the interview. I didn't pay too much attention to these two classes. What impressed me that java only has one StringBuffer? After reading the code, StringBuffer is thread-safe, that is, synchronized is available in the string operation methods.

So I opened the code comment and found that it was the StringBuilder that started with Jdk1.5, and added a non-lock class in later versions. It looks like it is to solve the efficiency problem in non-concurrent scenarios, no lock is required to improve the performance of large strings.

Well, it's good. I got a little bit of knowledge.

Out of curiosity, I read the code of these two classes, which is similar to String, but now chat [] does not contain final, this avoids the problem of generating a bunch of String objects during String operations.

char[] value;
  • Role of StringBuffer and StringBuilder

Now that we already have a String, what are the purposes of these two guys? The problem is related to the principle of String. Because the String is managed through the constant pool, this solves the problem of duplicate creation of the same String, but most strings are different, especially during String concatenation, if the String + is used for concatenation, a large number of String constants are generated, which consumes a lot of performance and space.

To solve this problem, StringBuffer is used. In essence, a variable character sequence does not need to generate new objects during string operations to improve memory usage.

Let's see how StringBuffer improves the splicing performance. View the StringBuffer/StringBuilder code (JDK1.5 +) and find that they all inherit from AbstractStringBuilder. A lot of code is actually completed in AbstractStringBuilder. This problem is caused by splicing. Here we will focus on the append method.

Public synchronized actstringbuilder append (String str) {if (str = null) return appendNull (); int len = str. length (); ensureCapacityInternal (count + len); // determine the capacity of str. getChars (0, len, value, count); // extract the str character and put it into the value array count + = len; // count accumulate return this ;}

The code is clear. The most important thing in the whole process is to use the getChars method of String to write the str value to the value of the current object. The getChars method of String is as follows:

public void getChars(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);}

It can be seen that an array is finally copied, because the value in AbstractStringBuilder is a variable char array. In this case, the string operation only needs to be performed on the char array. It will not generate new objects like String, so it will naturally become more efficient.


Note: This article is original. You are welcome to repost it. Please provide this article link clearly on the article page! If you think this article is good, please click the recommendation in the lower right corner. Thank you very much! Http://

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: 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.