String, StringBuilder, StringBuffer in Java, and stringbuffer in java
String in Java is an eternal topic. Let's talk about what I want to say.
1. String will never change. A Copy of the passed reference will stay well in its own nest no matter the wind or rain.
2. Reload "+" and StringBuilder
The connection string can be "+" or through the append () in StringBuilder. Sometimes "+" is used directly for laziness, but it is hard to understand whether it will affect the performance. First, describe this:
Through the bytecode reflected by jvm, when we use "+" to connect strings, JVM will automatically optimize them and introduce StringBuilder to connect strings. Therefore, for simple string connections, you can directly use "+" on the JVM to connect strings, but this is limited to simple concatenation (of course, you can also use it as hard, just... You know) for complex String concatenation, especially when loops are involved, we recommend using StringBuilder, because "+" is in the loop. During JVM implementation, the StringBuilder object is created repeatedly. StringBuilder can be used to make the code brief and simple, and only generate a StringBuilder object. It also allows you to specify the size in advance (if you already know the length of the final string, specify the size in advance, this can avoid re-allocating the buffer ).
3. StringBuilder and StringBuffer
StringBuffer is thread-safe, so the overhead is higher. If it does not involve thread security issues, we recommend using StringBuilder because it is more efficient;
!!! Try to avoid using append (a + "," + c); because this JVM will create a StringBuilder object for you to splice strings in parentheses.
Below is a simple example of StingBuilder.
Import java. util. random; public class TestStringBuilder {public static Random rand = new Random (); public String toString () {StringBuilder result = new StringBuilder ("["); for (int I = 0; I <25; I ++) {result. append (rand. nextInt (100); result. append (",") ;}// remove the last comma and space result. delete (result. length ()-2, result. length (); result. append ("]"); return result. toString ();} public static void main (String [] args) {TestStringBuilder ts = new TestStringBuilder (); System. out. println (ts );}}