Spaces:
Running
Running
| As stated earlier, Java STRINGS are MUTATION-FREE. | |
| This can cause problems in situations where, for example, a string should be assembled from very small pieces. | |
| As an example, consider a program that adds chunks to a string one at a time: | |
| String str = ""; | |
| for (int i=0; i<100; i++) { | |
| str += "x"; | |
| } | |
| Every time two strings are CONCATENATED, Java creates a NEW STRING. | |
| Thus, during the execution of the previous program, 101 strings are created. | |
| Although the strings that are discarded are not stored anywhere, they remain in MEMORY to haunt you. | |
| At some point, as free memory nears exhaustion, Java's automatic garbage collection removes the unnecessary objects from memory. | |
| However, this may result in a temporary slowdown for the user. | |
| =========================================== | |
| In 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. | |
| StringBuilder is a MUTABLE version of a string: its contents can therefore be changed after initialization. | |
| Let's consider the previous example implemented with the StringBuilder class: | |
| StringBuilder str = new StringBuilder(); | |
| for (int i=0; i<100; i++) { | |
| str.append("x"); | |
| } | |
| The StringBuilder class contains a variety of useful methods. | |
| The following example shows how the class works. | |
| Note 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. | |
| StringBuilder str = new StringBuilder("Hey everyone"); | |
| System.out.println(str); //Hey everyone | |
| // add at the end of string | |
| str.append("!!!"); | |
| System.out.println(str); //Hey everyone!!! | |
| // replaces between indexes 0 and 3 | |
| str.replace(0,3, "Bye"); | |
| System.out.println(str); //Bye everyone!!! | |
| // reverse order | |
| str.reverse(); | |
| System.out.println(str); //!!!enoyreve eyB | |
| Program outputs: | |
| Hey everyone | |
| Hey everyone!!! | |
| Bye everyone!!! | |
| !!!enoyreve eyB | |