Analysis of string _ Concatenation in Java

Source: Internet
Author: User

Absolutely original. indicate the source when reprinting,

Http://blog.csdn.net/izard999/article/details/6708433thank you!

There are a lot of string analysis on the Internet, so I will not bother to talk about other string knowledge!

This article only explains the String concatenation problem I encountered during the interview and recently saw an online machine question, so I want to share my understanding of String concatenation with you!

When I went to Huawei for an interview, the first question asked me to think about it. I came back to run the result on the camera and found that I was wrong, so I spent some time studying this:

String s = null;s += "abc";System.out.println(s);

The answer is nullabc!

With these three lines of code, I asked no more than 50 people, some senior people also had new users, and all answered wrong without running them .! It can be seen that many people learn Java quickly, and almost no one will study such things at the principle level and seemingly impractical, however, if you can understand the principle of String concatenation. It will be easy to solve!

Very early on, I knew that stringbuilder objects would be generated in the middle of String concatenation (stringbuffer was generated before jdk1.5), but I did not go deep into it at the time, leading to the mistake of writing this question at Huawei!

RuntimeThe concatenation of two strings str1 and str2 will first call String. valueof (OBJ). This obj is str1, while the implementation of string. valueof (OBJ) is return OBJ = NULL? "Null": obj. tostring (), then generate stringbuilder, call the stringbuilder (str1) constrmethod, initialize stringbuilder, the length is str1.length () + 16, and call append (str1 )!
Next, call stringbuilder. append (str2), concatenate the second string, and then call stringbuilder. tostring to return the result!

Therefore, the answer to that question comes from stringbuilder. append ("null"). append ("ABC"). tostring ();

After reading the analysis above, you will not encounter any other questions!

So what is the purpose of String concatenation?

When multiple threads are used, a synchronization monitor object is often used to synchronize the code synchronized (OBJ) in a code block. Only the same object is mutually exclusive and not the same object will be mutually exclusive!

Here is a machine question,

The existing program starts four threads to call testdo at the same time. dosome (Key, value) method, because testdo. the code in the dosome (Key, value) method is to pause for 1 second and then output the current time value in seconds. Therefore, four identical time values are printed, as follows:
4: 4: 1258199615
1: 1: 1258199615
3:3: 1258199615
1: 2: 1258199615
Modify the Code. If several threads call testdo. when the dosome (Key, value) method is passed in, the key is equal (equals is compared to true), then these threads should mutually exclusive queue output results, that is, when the keys of two threads are "1", one of them outputs results 1 second later than the other threads, as shown below:
4: 4: 1258199615
1: 1: 1258199615
3:3: 1258199615
1: 2: 1258199616
In short, when the specified keys in each thread are equal, the threads with the same keys should output time values in sequence every second (to use mutex). If the keys are different, it is executed in parallel (not mutually exclusive ). The original code is as follows:

View plainprint?
  1. Package SYN;
  2. // The test class cannot be modified.
  3. Public class test extends thread {
  4. Private testdo;
  5. Private string key;
  6. Private string value;
  7. Public test (string key, string key2, string value ){
  8. This. testdo = testdo. getinstance ();
  9. /* Constants "1" and "1" are the same object. The following line of code uses the "1" + "method to generate a new object,
  10. In order to achieve the content has not changed, it is still equal (both are still "1"), but the object is no longer the same effect */
  11. This. Key = Key + key2;
  12. This. value = value;
  13. }
  14. Public static void main (string [] ARGs) throws interruptedexception {
  15. Test A = new test ("1", "", "1 ");
  16. Test B = new test ("1", "", "2 ");
  17. Test C = new test ("3", "", "3 ");
  18. Test D = new test ("4", "", "4 ");
  19. System. Out. println ("begin:" + (system. currenttimemillis ()/1000 ));
  20. A. Start ();
  21. B. Start ();
  22. C. Start ();
  23. D. Start ();
  24. }
  25. Public void run (){
  26. Testdo. dosome (Key, value );
  27. }
  28. }
  29. Class testdo {
  30. Private testdo (){}
  31. Private Static testdo _ instance = new testdo ();
  32. Public static testdo getinstance (){
  33. Return _ instance;
  34. }
  35. Public void dosome (Object key, string value ){
  36. // The code must be partially synchronized in braces and cannot be changed!
  37. {
  38. Try {
  39. Thread. Sleep (1000 );
  40. System. Out. println (Key + ":" + value + ":"
  41. + (System. currenttimemillis ()/1000 ));
  42. } Catch (interruptedexception e ){
  43. E. printstacktrace ();
  44. }
  45. }
  46. }
  47. }

There are many ways to solve this problem. The indispensable step is to use synchronized (o) in the dosome method to synchronize the code block that has been written with comments. Some may say:

I directly synchronized (key), isn't it done .? This type of person must be at the beginner level!

As mentioned above, synchronized (OBJ) is mutually exclusive to the same object. If it is not the same object, it will not be mutually exclusive! Let's take a look at what the constructor in the test class has done for the key?

This. Key = Key + key2;

For String concatenation, if it is the concatenation of two constants, you will be the same object regardless of the number of Concatenated strings. This isCompile timeThe compiler automatically performs optimization (if you want to know the specific principles, search for them online ).

String a = "a" + "b";String b = "a" + "b";System.out.println(a == b);

This code output is true. No problem

However, once a variable is involved, when I run it in red or bold, the concatenation string will generate the stringbuilder. But how does one return the string after splicing?

The implementation in stringbuilder. tostring () is new string (char value [], int offset, int count). Since it is returned by creating a string, calling tostring once is a different object.

String a = "a";String b = "b";String s1 = a + b;String s2 = a + b;System.out.println(s1 == s2);

This output is false!

Therefore, synchronized (key) cannot be used for synchronization in that computer question. If you have read this article with full patience, you should know how to use synchronized (key) synchronized that code!

That is, modify this. Key = Key + key2 in the test constructor to this. Key = key;

Because strings do not involve concatenation, as long as they are not new, they all point to the same object!

Of course, you can also throw the key to the set and use the contains (OBJ) of the Set to judge the multi-threaded question. If the set exists, take the set, otherwise, add it to the set, but remember to use the set under the concurrent package. Otherwise, concurrentmodificationexception may be thrown.

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.