The + operator

In terms of posture, the “+” operator has to be the most common type of string concatenation.

Stringchenmo="Shanghai";
Stringwanger="Shang Xue Tang";

System.out.println(chenmo+wanger);Copy the code

Let’s decompile this code using JAD.

Stringchenmo="\\u6C89\\u9ED8"; / / Shanghai Stringwanger ="\\u738B\\u4E8C"; Println ((newStringBuilder(String.Valueof (chenmo))).appEnd (wanger).toString()));Copy the code

Heck, the original compilation replaced the “+” operator with the Append method of StringBuilder. In other words, the “+” operator is just a formalism for concatenating strings, making it easier for developers to use, simpler to look at, and smoother to read. It’s a kind of Java syntactic candy.

Shanghai is still school official website this nothing to say, there are many years of Java development senior teachers and architects for everyone to bring the latest version of 2020 for the enterprise, the new research and development of Python,Java, big data, artificial intelligence and other teaching videos and project source code and documents!!

StringBuilder

Aside from the “+” operator, StringBuilder’s append method is the second commonly used string concatenation position.

Append: StringBuilder appEnd: StringBuilder appEnd: StringBuilder appEnd

publicStringBuilderappend(Stringstr){
super.append(str);
returnthis;
}Copy the code

AbstractStringBuilder > AbstractStringBuilder > AbstractStringBuilder < AbstractStringBuilder >

publicAbstractStringBuilderappend(Stringstr){
if(str==null)
returnappendNull();
intlen=str.length();
ensureCapacityInternal(count+len);
str.getChars(0,len,value,count);
count+=len;
returnthis;
}Copy the code

1) Check whether the concatenated string is null, if so, treat it as string “NULL”. The appendNull method has the following source code:

privateAbstractStringBuilderappendNull(){
intc=count;
ensureCapacityInternal(c+4);
finalchar[]value=this.value;
value[c++]='n';
value[c++]='u';
value[c++]='l';
value[c++]='l';
count=c;
returnthis;
}Copy the code

2) Whether the length of the character array after concatenation exceeds the current value. If so, expand and copy it. The ensureCapacityInternal method is as follows:

privatevoidensureCapacityInternal(intminimumCapacity){
//overflow-consciouscode
if(minimumCapacity-value.length>0){ value=Arrays.copyOf(value, newCapacity(minimumCapacity)); }}Copy the code

3) Copy the concatenated string STR into the destination array value.

str.getChars(0,len,value,count)Copy the code

StringBuffer

StringBuffer comes first and StringBuilder comes second, so they’re kind of like twins, they have everything they need, except that the older StringBuffer is thread-safe because it takes two more breaths of fresh air.

publicsynchronizedStringBufferappend(Stringstr){
toStringCache=null;
super.append(str);
returnthis;
}Copy the code

The append method of the StringBuffer class uses the synchronized keyword to override toStringCache = null.

Synchronized is a very familiar keyword in Java and is a type of synchronization lock. The methods it decorates are called synchronous methods and are thread-safe.

Concat method of the String class

In terms of posture alone, the concat method of The String class is like the Append of the StringBuilder class.

Stringchenmo="Shanghai";
Stringwanger="Shang Xue Tang";

System.out.println(chenmo.concat(wanger));Copy the code

While writing this article, I suddenly had a wonderful idea. Suppose there are two lines of code:

chenmo+=wanger
chenmo=chenmo.concat(wanger)Copy the code

How different are they?

Chenmo += wanger = new StringBuilder(String.Valueof (chenmo))).appEnd (wanger).toString().

To explore the difference between the “+” operator and concat, look at the difference between the append and concat methods.

The source code for the append method has been analyzed before. Let’s take a look at the source of the concat method.

publicStringconcat(Stringstr){
intotherLen=str.length();
if(otherLen==0){
returnthis;
}
intlen=value.length;
charbuf[]=Arrays.copyOf(value,len+otherLen);
str.getChars(buf,len);
returnnewString(buf,true);
}Copy the code

1) If the length of the concatenated string is 0, return the string before concatenation.

if(otherLen==0){
returnthis;
}Copy the code

2) Copy the character array value of the original string into the variable buf array.

charbuf[]=Arrays.copyOf(value,len+otherLen);Copy the code

3) Copy the concatenated string STR into the character array buf and return the new string object.

str.getChars(buf,len);
returnnewString(buf,true);Copy the code

Through source code analysis, we can roughly draw the following conclusions:

1) If the concatenated string is null, a NullPointerException will be thrown during concat and the “+” operator will be treated as a “NULL” string.

2) Concat is more efficient if the concatenated string is an empty string (“”). After all, you don’t need a New StringBuilder object.

3) Concat becomes less efficient if a large number of strings are concatenated, because the more string objects you create, the more overhead.

Attention!!

Weakly ask ah, still have the classmate that uses JSP? The “+” operator is not allowed to concatenate strings in EL expressions. Instead, concat is used.

${chenmo.concat('-').concat(wanger)}Copy the code

Join method of String class

JDK 1.8 provides a new String concatenation posture: the String class adds a static method called JOIN.

Stringchenmo="Shanghai";
Stringwanger="Shang Xue Tang";
Stringcmower=String.join("",chenmo,wanger);
System.out.println(cmower);Copy the code

The first argument is a string concatenation, for example:

Stringmessage=String.join("-"."Shanghai".""."Interesting.");Copy the code

The output is “Still Learning-Java”

Let’s look at the source of the join method:

publicstaticStringjoin(CharSequencedelimiter,CharSequence... elements){ Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); //NumberofelementsnotlikelyworthArrays.streamoverhead. StringJoinerjoiner=newStringJoiner(delimiter);for(CharSequencecs:elements){
joiner.add(cs);
}
returnjoiner.toString();
}Copy the code

There’s a new class called StringJoiner, and it looks like a 6, and it’s very easy to read. StringJoiner is a class in the java.util package that constructs a sequence of characters rejoined by delimiters. Limited by space, this article will not do too much introduction, interested students can go to know.

StringUtils.join

Practical projects, when we deal with string, often use this class — org.apache.com mons. Lang3. StringUtils, the class of the join method is a kind of new posture of string concatenation.

Stringchenmo="Shanghai";
Stringwanger="Shang Xue Tang";

StringUtils.join(chenmo,wanger);Copy the code

This method is better at concatenating strings from arrays without worrying about NullPointerExceptions.

StringUtils.join(null)=null
StringUtils.join([])=""
StringUtils.join([null])=""
StringUtils.join(["a"."b"."c"]) ="abc"
StringUtils.join([null,""."a"]) ="a"Copy the code

Looking at the source code, we can see that the StringBuilder is still used internally.

publicstaticStringjoin(finalObject[]array,Stringseparator,finalintstartIndex,finalintendIndex){
if(array==null){
returnnull;
}
if(separator==null){
separator=EMPTY;
}

finalStringBuilderbuf=newStringBuilder(noOfItems*16);

for(inti=startIndex; i<endIndex; i++){if(i>startIndex){
buf.append(separator);
}
if(array[i]! =null){ buf.append(array[i]); } } returnbuf.toString(); }Copy the code

When you read this, you will have such a feeling: I rely on (sound to be prolonged), did not expect ah did not expect, string stitching fully 6 postures ah, back home at night must try one by one.



If you want to learn more about Java, follow me and update me daily