Skip to content

Commit 65e26a6

Browse files
authored
Updated StringBuilder.md file
1 parent f124895 commit 65e26a6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

lessons/string-builder.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,48 @@ order: "6B"
55
section: "Strings In Depth"
66
description: "learn strings in depth"
77
---
8+
## Introduction
9+
10+
String Builder is a separate class just like Strings, which allows us to modify the values(mutability).
11+
### Need of String Builder:
12+
As we know that Strings are immutable ,because of which
13+
each and every time we need to create an object and that object will have no reference in later cases while running the loop , hence there will be huge memory wastage and due to this we use String Builder.
14+
### Code:
15+
```java
16+
public class SB {
17+
public static void main(String[] args) {
18+
StringBuilder builder=new StringBuilder();
19+
for(int i = 0;i<26;i++){
20+
char ch=(char) ('a'+i);
21+
builder.append(ch);
22+
}
23+
System.out.println(builder.toString());
24+
}
25+
}
26+
27+
```
28+
### Code Explanation:
29+
* This is a simple code which demonstrates the use of String Builder class to print all alphabets from a-z, and to show how efficient it is in space and time complexity.
30+
* So inside the main function, we create a StringBuilder using "new" keyword, just like how we use to create for Strings.
31+
* Now inside the ```for``` loop we take ASCII value of the character 'a' and add it to the iterating variable ```i``` and finally typecast the ASCII value to a character and assign it to ```ch```.
32+
* In next step we add(```append```) each character to the builder and finally print it after converting them to String format by calling toString() Method.
33+
34+
35+
# Code Analysis:
36+
1. #### Now if we analyze the Time Complexity of using **Strings** for the above example:
37+
38+
```[a,ab,abc,abcd,...........,abcdefghijklmnopqrstuvwxy] ```
39+
40+
* Here, Size of each items are 1+2+3+4...+26 (N). This can be represented as N(N+1) /2 .
41+
42+
* After eliminating constants and less dominating terms , we finally obtain O(N^2).
43+
44+
* All of these large Strings will have no reference variable pointing towards it. [Wastage of Space].
45+
46+
2. #### Now if we analyze the Time Complexity of using **String Builder** for the above example:
47+
48+
* Here instead of creating new object every time , it makes changes in the exsiting object itself[like how Arrays does], hence saving memory space and time.
49+
For example:
50+
```["abc"+d -> "abcd"]```
51+
52+
* Due to this the Time Complexity is O(N).

0 commit comments

Comments
 (0)