Java string concatenation method and usage scenarios
1. Using +
the operator
code example
String str1 = "Hello, ";
String str2 = "World!";
String result = str1 + str2;
scenes to be used
- Good for small scale string concatenation.
- When there are fewer splicing operations, the readability is good and the code is concise.
2. Using StringBuilder
the class
code example
StringBuilder builder = new StringBuilder();
builder.append("Hello, ");
builder.append("World!");
String result = builder.toString();
scenes to be used
- Suitable for mass concatenation of strings in a single-threaded environment.
- Can improve performance when strings need to be modified frequently.
3. Using StringBuffer
the class
code example
StringBuffer buffer = new StringBuffer();
buffer.append("Hello, ");
buffer.append("World!");
String result = buffer.toString();
scenes to be used
- Suitable for concatenating strings in large numbers in a multi-threaded environment.
- Used when thread safety is required.
4. String.concat
How to use
code example
String str1 = "Hello, ";
String result = str1.concat("World!");
scenes to be used
- When you need to append one string to the end of another.
- Useful when splicing operations are explicitly indicated.
5. String.format
How to use
code example
String result = String.format("%s%s", "Hello, ", "World!");
scenes to be used
- When formatted string concatenation is required.
- It is suitable for occasions that need to insert variables or use specific formats.