Notes › Java
String, StringBuilder and StringBuffer
String is immutable
Once a String object is created, its characters can never change. Methods like toUpperCase() or concat() return a new string.
String s = "hello";
s.toUpperCase(); // returns "HELLO", but s is unchanged
s = s.toUpperCase(); // now s points to a new object
Why immutable?
- String pool — literals can be shared safely.
- Security — file paths, URLs and class names can't be changed after checks.
- Thread-safe for free.
- Hash code can be cached — great as
HashMapkeys.
Creating strings
String a = "java"; // pooled literal
String b = new String("java"); // new heap object (avoid)
String c = b.intern(); // the pooled copy → a == c is true
Common methods
| Method | Result for s = "Hello World" |
|---|---|
s.length() |
11 |
s.charAt(4) |
'o' |
s.substring(6) / s.substring(0, 5) |
"World" / "Hello" |
s.indexOf("o") / s.lastIndexOf("o") |
4 / 7 |
s.contains("World") |
true |
s.equals("hello world") / equalsIgnoreCase |
false / true |
s.compareTo("Hi") |
negative ('e' < 'i') |
s.split(" ") |
["Hello", "World"] |
s.replace('l', 'L') |
"HeLLo WorLd" |
s.trim() / s.strip() |
removes spaces at both ends |
s.toCharArray() |
char[] |
String.valueOf(42) / Integer.parseInt("42") |
"42" / 42 |
String.join("-", list) |
"a-b-c" |
The + in a loop problem
String s = "";
for (int i = 0; i < 100000; i++) s += i; // creates 100,000 new strings → O(n²)
Each += copies the whole string. Use StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) sb.append(i); // amortised O(1) per append
String s = sb.toString();
StringBuilder methods
StringBuilder sb = new StringBuilder("abc");
sb.append("def"); // abcdef
sb.insert(0, "X"); // Xabcdef
sb.reverse(); // fedcbaX
sb.deleteCharAt(0); // edcbaX
sb.setCharAt(0, 'E'); // EdcbaX
sb.length(); // 6
Reversing a string or checking a palindrome? new StringBuilder(s).reverse().toString().
String vs StringBuilder vs StringBuffer
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | ❌ | ✅ | ✅ |
| Thread-safe | ✅ (immutable) | ❌ | ✅ (synchronized) |
| Speed for many changes | slow | fastest | slower than StringBuilder |
| Use when | value doesn't change | building strings in one thread | building strings shared across threads (rare) |
== vs .equals()
==compares references (same object?)..equals()compares content.
String x = "hi", y = new String("hi");
x == y; // false
x.equals(y); // true
Useful character tricks (DSA)
char c = 'b';
int idx = c - 'a'; // 1
boolean d = Character.isDigit(c); // false
char up = Character.toUpperCase(c); // 'B'
int[] freq = new int[26]; // count letters
for (char ch : s.toCharArray()) freq[ch - 'a']++;
Interview one-liners
- String is immutable and
final(cannot be subclassed). - How many objects does
new String("abc")create? Up to two: one in the pool (if not already there) and one on the heap. - Use
StringBuilderfor concatenation in loops. - Strings in
switchwork since Java 7 (useshashCode+equals). - Practise string problems in the Strings section.