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 theStringBuilderclass instead to improve performance. TheStringBuilderclass is mutable. When you make operations on aStringBuilderobject, the original object is mutated (unlike theStringclass) and returns the (mutated) original object. Except improvement of performance, theStringBuilderclass also offer many other useful methods for string operations that are not included in theStringclass.If you want to read or write large text (e.g. more than 100M), you can use
BufferedReadandBufferedWriterto 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);