Comments¶
String is a immutable class in Java. Extensive operations on strings (e.g.,
+
in a big loop) is usually very slow before Java 7 (the+
operator is optimized by the compiler automatically starting from Java 7). To avoid this problem (in older versions of Java), you can use theStringBuilder
class instead to improve performance. TheStringBuilder
class is mutable. When you make operations on aStringBuilder
object, the original object is mutated (unlike theString
class) and returns the (mutated) original object. Except improvement of performance, theStringBuilder
class also offer many other useful methods for string operations that are not included in theString
class.If you want to read or write large text (e.g. more than 100M), you can use
BufferedRead
andBufferedWriter
to improve performance.There is no built-in sort method for String. To sort characters in a string, you can first convert the string into a char array, sort the char array and convert back.
You want to the equals method to compare string most of time unless you know for sure that comparing references is the right way.
String.split¶
Splitting an empty string results in a String array containing a single empty string. That is a String array of length 1 (instead of an emtpy String array) is return! Be aware of it as it might or might not what you want.
String[] arr = "".split(" ");
System.out.println(arr.length);