KaiquanMah commited on
Commit
98e9587
·
verified ·
1 Parent(s): aab9852

StringBuilder str = new StringBuilder("<urStr>");

Browse files
Week 3: Objects, files and exceptions/14a Class StringBuilder ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ As stated earlier, Java STRINGS are MUTATION-FREE.
2
+ This can cause problems in situations where, for example, a string should be assembled from very small pieces.
3
+ As an example, consider a program that adds chunks to a string one at a time:
4
+
5
+ String str = "";
6
+ for (int i=0; i<100; i++) {
7
+ str += "x";
8
+ }
9
+
10
+
11
+ Every time two strings are CONCATENATED, Java creates a NEW STRING.
12
+ Thus, during the execution of the previous program, 101 strings are created.
13
+
14
+ Although the strings that are discarded are not stored anywhere, they remain in MEMORY to haunt you.
15
+ At some point, as free memory nears exhaustion, Java's automatic garbage collection removes the unnecessary objects from memory.
16
+ However, this may result in a temporary slowdown for the user.
17
+
18
+ ===========================================
19
+
20
+
21
+ 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.
22
+ StringBuilder is a MUTABLE version of a string: its contents can therefore be changed after initialization.
23
+
24
+ Let's consider the previous example implemented with the StringBuilder class:
25
+
26
+ StringBuilder str = new StringBuilder();
27
+ for (int i=0; i<100; i++) {
28
+ str.append("x");
29
+ }
30
+
31
+
32
+
33
+ The StringBuilder class contains a variety of useful methods.
34
+ The following example shows how the class works.
35
+ 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.
36
+
37
+ StringBuilder str = new StringBuilder("Hey everyone");
38
+ System.out.println(str); //Hey everyone
39
+
40
+ // add at the end of string
41
+ str.append("!!!");
42
+ System.out.println(str); //Hey everyone!!!
43
+
44
+ // replaces between indexes 0 and 3
45
+ str.replace(0,3, "Bye");
46
+ System.out.println(str); //Bye everyone!!!
47
+
48
+ // reverse order
49
+ str.reverse();
50
+ System.out.println(str); //!!!enoyreve eyB
51
+
52
+
53
+ Program outputs:
54
+ Hey everyone
55
+ Hey everyone!!!
56
+ Bye everyone!!!
57
+ !!!enoyreve eyB
58
+
59
+
60
+