KaiquanMah/TurkuBasicOOPinJava
0
1As stated earlier, Java STRINGS are MUTATION-FREE. 2This can cause problems in situations where, for example, a string should be assembled from very small pieces. 3As an example, consider a program that adds chunks to a string one at a time:4 5String str = "";6for (int i=0; i<100; i++) {7 str += "x";8}9 10 11Every time two strings are CONCATENATED, Java creates a NEW STRING. 12Thus, during the execution of the previous program, 101 strings are created. 13 14Although the strings that are discarded are not stored anywhere, they remain in MEMORY to haunt you. 15At some point, as free memory nears exhaustion, Java's automatic garbage collection removes the unnecessary objects from memory. 16However, this may result in a temporary slowdown for the user.17 18===========================================19 20 21In situations where it is necessary to change a string frequently, it is usually more sensible to use the StringBuilder class instead of the String class. 22StringBuilder is a MUTABLE version of a string: its contents can therefore be changed after initialization.23 24Let's consider the previous example implemented with the StringBuilder class:25 26StringBuilder str = new StringBuilder();27for (int i=0; i<100; i++) {28 str.append("x");29}30 31 32 33The StringBuilder class contains a variety of useful methods. 34The following example shows how the class works. 35Note that the class is built into Java (i.e., it is included in the java.lang package), so it does not need to be explicitly introduced by an import statement.36 37StringBuilder str = new StringBuilder("Hey everyone");38System.out.println(str); //Hey everyone39 40// add at the end of string41str.append("!!!");42System.out.println(str); //Hey everyone!!!43 44// replaces between indexes 0 and 345str.replace(0,3, "Bye");46System.out.println(str); //Bye everyone!!!47 48// reverse order49str.reverse();50System.out.println(str); //!!!enoyreve eyB51 52 53Program outputs:54Hey everyone55Hey everyone!!!56Bye everyone!!!57!!!enoyreve eyB58 59 60 61 