Skip to content

Commit c4f1173

Browse files
committed
docs: explain String immutability and compare concat vs StringBuilder performance
WHAT was added: - Implemented two methods in `StringImmutable`: 1. `appendNtimesUsingStringConcat(char c, int n)` → builds a string by repeated `+=` concatenation. - Inefficient due to immutability of String (O(n²) time complexity). 2. `appendNtimesUsingStringBuilder(char c, int n)` → builds a string using `StringBuilder.append()`. - Efficient (O(n) time complexity), since StringBuilder is mutable. WHY this matters: - Demonstrates the **performance cost of immutability** in Java Strings. - Shows how `StringBuilder` is the preferred solution for repeated concatenation, especially inside loops. KEY CONCEPTS EXPLAINED: - **String**: - Immutable: any concatenation creates a new object. - Leads to quadratic performance when repeatedly appending in loops. - **StringBuilder**: - Mutable: allows in-place modification. - append() runs in amortized O(1), overall O(n) for n appends. - Recommended for dynamic text building in single-threaded contexts. EXAMPLE OUTPUT: - `appendNtimesUsingStringConcat('A', 5)` → `AAAAA` - `appendNtimesUsingStringBuilder('B', 3)` → `BBB` REAL-WORLD APPLICATIONS: - ❌ Avoid `+=` in loops (e.g., building logs, generating test strings, assembling reports). - ✅ Use `StringBuilder` when constructing large or dynamic strings efficiently. - ✅ Use `StringBuffer` when thread-safety is required in multi-threaded apps. RULE OF THUMB: - Use String for short, constant values. - Use StringBuilder for frequent concatenations in loops. - Use StringBuffer if multiple threads modify the same string. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent ce221f0 commit c4f1173

File tree

1 file changed

+117
-0
lines changed

1 file changed

+117
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
### 1. Class Declaration:
2+
3+
```java
4+
public class StringImmutable {
5+
```
6+
Here, we declare a public class `StringImmutable`. This class will contain the methods we need for string operations.
7+
The class name is chosen to reflect that we're dealing with string immutability (as strings in Java are immutable).
8+
9+
### 2. Main Method:
10+
11+
```java
12+
public static void main(String[] args) {
13+
```
14+
This is the entry point of the Java program. It's a standard `main` method that Java looks for when you run the program.
15+
The method is `static`, meaning you don't need to create an instance of the class to run it.
16+
17+
Inside this method, we will demonstrate how to use the two string manipulation methods (`appendNtimesUsingStringConcat`
18+
and `appendNtimesUsingStringBuilder`).
19+
20+
### 3. **Creating an Instance of `StringImmutable`:**
21+
22+
```java
23+
StringImmutable si = new StringImmutable();
24+
```
25+
Since the methods `appendNtimesUsingStringConcat` and `appendNtimesUsingStringBuilder` are not `static`,
26+
we create an instance of `StringImmutable` (`si`) so we can call those methods on this instance.
27+
28+
### 4. **Using `appendNtimesUsingStringConcat`:**
29+
30+
```java
31+
String result1 = si.appendNtimesUsingStringConcat('A', 5);
32+
System.out.println(result1); // Output: AAAAA
33+
```
34+
Here, we call the method `appendNtimesUsingStringConcat` with two arguments:
35+
- `'A'` (the character we want to append).
36+
- `5` (the number of times we want to append the character to the string).
37+
38+
The method returns a string of `5` repeated `'A'` characters, and print it.
39+
40+
### 5. **Using `appendNtimesUsingStringBuilder`:**
41+
42+
```java
43+
String result2 = si.appendNtimesUsingStringBuilder('B', 3);
44+
System.out.println(result2); // Output: BBB
45+
```
46+
Similarly, we call `appendNtimesUsingStringBuilder`, passing:
47+
- `'B'` (the character to append).
48+
- `3` (the number of times to append it).
49+
50+
This method uses a `StringBuilder` (more efficient for repeated string concatenations) and returns a string of `3`
51+
repeated `'B'` characters, which is printed.
52+
53+
### 6. **Method 1: `appendNtimesUsingStringConcat`:**
54+
55+
```java
56+
public String appendNtimesUsingStringConcat(char c, int n) {
57+
String str = "";
58+
for (int i = 0; i < n; i++) {
59+
str += c; // O(s) where s = length(str)
60+
}
61+
return str;
62+
}
63+
```
64+
This method demonstrates string concatenation using the `+` operator, which is known to be inefficient for large numbers
65+
of concatenations (due to the string immutability in Java).
66+
67+
- `String str = "";` initializes an empty string.
68+
- The `for` loop runs `n` times (based on the number you pass).
69+
- Each iteration appends the character `c` to `str` using `str += c;`.
70+
71+
In Java, this causes the string to be copied and a new one to be created every time because strings are **immutable** (cannot be changed). This operation takes longer as the string grows, resulting in an overall time complexity of `O(n^2)` (quadratic), where `n` is the number of characters you're concatenating.
72+
- Finally, the method returns the concatenated string.
73+
74+
### 7. **Method 2: `appendNtimesUsingStringBuilder`:**
75+
76+
```java
77+
public String appendNtimesUsingStringBuilder(char c, int n) {
78+
StringBuilder sb = new StringBuilder();
79+
for (int i = 0; i < n; i++) {
80+
sb.append(c); // O(1)
81+
}
82+
return sb.toString();
83+
}
84+
```
85+
86+
This method demonstrates the more efficient approach using `StringBuilder` for string concatenation.
87+
- `StringBuilder sb = new StringBuilder();` creates a `StringBuilder` object. Unlike strings, `StringBuilder` is
88+
mutable, meaning it can grow without creating new objects each time.
89+
- The `for` loop runs `n` times and appends the character `c` to the `StringBuilder` with `sb.append(c);`.
90+
This operation is `O(1)` (constant time) because `StringBuilder` efficiently handles string growth internally.
91+
- After the loop, `sb.toString()` converts the `StringBuilder` object into a regular string and returns it.
92+
93+
Using `StringBuilder` results in better performance with a time complexity of `O(n)` (linear time),
94+
as it avoids the costly copying of strings during each iteration.
95+
96+
### 8. **Why These Methods Matter:**
97+
- The first method (`appendNtimesUsingStringConcat`) uses a simple `+=` operator, but it has inefficient
98+
time complexity due to the immutability of strings in Java.
99+
It works fine for small `n` values, but for large `n`, the performance degrades drastically.
100+
- The second method (`appendNtimesUsingStringBuilder`) uses `StringBuilder`, which is designed to be
101+
more efficient for such operations.
102+
103+
It performs better because `StringBuilder` is mutable and avoids the overhead of string concatenation.
104+
105+
### Summary:
106+
- The code demonstrates two ways to build a string by repeating a character multiple times.
107+
- The first approach uses string concatenation (`+=`), which has poor performance for large inputs.
108+
- The second approach uses `StringBuilder`, which is optimized for this task and performs much better.
109+
- We also included a simple example in the `main` method to show how both methods can be used.
110+
111+
String is immutable, meaning you can't change it once created.
112+
When you concatenate two strings, it doesn’t simply add one string at the end of another;
113+
it creates a new string (ouch).
114+
115+
Use a StringBuilder instead (or string.join() on a list in Python), which essentially is a List<Character>.
116+
· String += c → linear
117+
· StringBuilder.append(c) → constant

0 commit comments

Comments
 (0)