Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

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?

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()

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

More Java notes