问题
There are way too many ways to concatenate strings and add variable values in Java. How should I select one (pros, cons, best use cases, etc).
- MessageFormat.format
- String.format
- "string a" + "string b"
- StringBuilder
- StringBuffer
- String.concat
- Streams
- String.join()
- Apache Commons’ StringUtils
- Google Guava’s Joiner
- ...
回答1:
MessageFormat.format() - Used for dynamically created strings, where parts of the string are positioned and the arguments fill up the place.
MessageFormat.format("My name is {0}. I am {1} years old", "Vignesh", 24);
String.format() - Like position numbering in MessageFormat, it accepts the argument type specifiers.
String.format("Pi is %.2f", 3.14)
String+String - string+string produces a new string leaving the older ones in the garbage, which gets cleared later by JVM. It internally gets converted to StringBuilder.append() and toString() methods.
hello+world=helloworld
null+hello=nullhello
String.concat() - Unlike string+string, if the object on which concat method is called is null, NullPointerException will be thrown.
String a = null, b="hello"; a.concat(b) throws NullPointerException
StringBuffer - They are mutable but they are slower as the methods inside them are synchronized. ie., thread safe
StringBuffer sb = new StringBuffer();
sb.append("hello").append("world");
sb.toString();
StringBuilder - They are mutable and faster than StringBuffer, but not thread safe
StringBuilder sb = new StringBuilder();
sb.append("hello").append("world");
sb.toString();
String.join - If the strings to be concatenated is in the form of array, its better to use String.join rather than looping through the array and appending using a StringBuilder, which String.join does it already inernally. If the array passed is null
, it throws NullPointerException
.
String[] a = {"hello", "world"};
String.join("", a)
StringUtils.join - If the strings to be concatenated is in the form of array, this can also be used. It internally uses StringBuilder. But just for string concatenation there is no need to include a jar. It precalcualtes the capacity
of the StringBuilder object based on the numnber of elements in the array. If the array passed is null
, it doesn't throws exception but just returns null
string.
String[] a = {"hello", "world"};
StringUtils.join(a, "")
来源:https://stackoverflow.com/questions/53214160/java-best-practices-on-string-concatenation-and-variable-substituittion-in-stri