The string class of knowledge points

Source: Internet
Author: User

Objective

There's a code like this.

 1 public class< Span style= "color: #000000;" > Testmain2 {3 public static void4  {; 6 String str1 = "123" ; 7 System.out.println (str0 == str1); }9}        

What is the result of the operation? The answer is of course true. Yes, the answer is true, but why is it? A lot of people first reaction is certainly two "123" of the string of course equal Ah, this also want to. But the "= =" Comparison in Java is not the value of two objects at all, but rather the comparison of two objects are equal, and two strings are "123" What does it matter? Or we'll change the program.

1Publicclass Testmain2 {3 public static void main (string[] args) 4  {5 String str2 = new String ("234" new String ("234" ); 7 System.out.println (str2 == STR3); }9}       

The result is false, because although two string objects are "234", str2 and STR3 are two different references, so the return is false. OK, return true around the first paragraph of code, return FALSE for the second paragraph, and start the content of the article.

Why String=string?

There is an area in the JVM called a constant pool, and for constant pools, I specifically mention http://www.cnblogs.com/xrq730/p/4827590.html when I write a virtual machine. The data in a constant pool is some of the data that was determined during compilation and saved in the compiled. class file. In addition to all 8 basic data types (char, byte, short, int, long, float, double, Boolean), there are constant values for string and its arrays, plus some symbolic references that appear as text.

Java stack is characterized by fast access (than heap blocks), but small space, the data life cycle fixed, only to survive to the end of the method . We define the Boolean B = true, char c = ' C ', String str = "123", these statements, which we split into several parts of the view:

1,True, C, 123, these equals to the right refers to the content can be determined during compilation, are maintained in the constant pool

2,B, C, str the first occurrence on the left side of the equals sign is a reference to the address of the data in the constant pool to the right of the equal sign.

3,Boolean, char, String These are the types of references

The stack has a feature that is data sharing . Back to our first example, line fifth string str0 = "123", compile, create a constant in the constant pool "123", and then go to the sixth row of string str1 = "123", first go to the constant pool to find there is no this "123", found that there, STR1 also points to "123" in the constant pool, so str0 = = Str1 of line seventh returns true because Str0 and str1 point to the address of the string "123" in the constant pool. Of course, if string str1 = "234", it is not the same, because there is no "234" in the constant pool, so a "234" is created in the constant pool, and then str1 represents the address of this "234". The analysis of String, in fact, the other basic data types are the same: first look at the constant pool there is no data to be created, there is the address of the return data, do not create one .

What is the second example? Java Virtual machine interpreter each encounter a new keyword, will be in the heap memory to open a piece of memory to hold a string object, so str2, Str3 point to the heap memory, although the storage is equal to "234", but because it is two different heap memory, so str2 = = STR3 return is still false, find a picture on the web to show this concept:

Why use StringBuilder and stringbuffer to stitch strings?

There must be a principle in development that "use StringBuilder and StringBuffer to stitch strings", but why? Use a piece of code to analyze:

1PublicClassTestmain{ 3 public static void {; 6 str + = "222" ; ; 8 str + = " 444 "; 9 10 }11}     

Analyze the code to run the process:

1, line 5th, go to the constant pool to find "111", not found, a constant pool to create a, str points to the constant pool "111"

2, the 6th line, go to the constant pool to find the stitching after the "111222", not found, the constant pool to create a, str points to the constant pool "111222"

3, the 7th line, go to the constant pool to find the stitching after the "111222111", not found, the constant pool to create a, str points to the constant pool "111222111"

4, the 8th line, go to the constant pool to find the stitching after the "111222111444", not found, the constant pool to create a, str points to the constant pool "111222111444"

See, that's the downside of string concatenation. We eventually only needed "111222111444", but we created so many intermediate constants "111", "111222", "111222111" in the constant pool. This means that string concatenation may result in a large number of useless constants in the constant pool (in case of the constant pool created), consuming memory space, although one or two strings are nothing but a little, String concatenation is used everywhere in the code, which is a huge drain .

At the same time, this is the reason to use StringBuilder and StringBuffer, take StringBuilder as an example:

1PublicClassTestmain2{3Publicstatic void main ( String[] args)  { 5 StringBuilder sb = new StringBuilder ("111"  6 Sb.append ("222"  7 Sb.append (" 111 ");  8 Sb.append ("111"  9 Sb.append ("444"  System.out.println (sb.tostring ()); }12}       

StringBuffer and StringBuilder the same principle, is nothing more than to maintain a char array at the bottom, each time append to the char array to put characters, in the final sb.tostring (), with a new String () The method converts the contents of the char array into a string, so that the constant pool creates a resulting string that, in the case where the string needs to be spliced, especially a large number of stitching, saves a lot of space in the constant pool.

StringBuffer and StringBuilder use exactly the same, the only difference is that StringBuffer is thread-safe, it synchronizes all methods, StringBuilder is thread insecure , So in a scenario that doesn't involve thread safety, such as inside a method, use StringBuilder as much as possible to avoid the consumption of synchronization. In addition, StringBuffer and StringBuilder also have an optimization point, if you can estimate the length of the string to be spliced, try to use the constructor to specify their length, to avoid the consumption of array expansion , This will be written later when the list is written.

Beware of traps.

Although it is said not to use "+" splicing string, because it will produce a lot of useless constants, but also not not, such as can be used in the following way:

 1 public class< Span style= "color: #000000;" > Testmain2 {3 public static void4  {; 6  System.out.println (str); }8}       

To do this, when actually compiled, Java will be "111", "222", "333", "444" are spliced directly together as a whole string to see, and then to STR, in fact, in the constant pool only a "111222333444", and will not produce useless constants. However, the main reason for this is that there are two points:

1, the example is relatively simple, but in fact a large number of "+" will lead to code readability is very poor

2, the content to be spliced may be obtained from various places, such as calling interface, from the. properties file, from the. xml file, in such a scenario, although the use of multiple "+" way is not not possible, but will cause inconvenient

The string class of knowledge points

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.