← Learning Hub
Beginner

ArrayList, Strings and StringBuilder

ArrayList is the everyday list in Java - it grows as you add items. Strings are immutable, so building text in loops should use StringBuilder. Both appear in most interview questions.

ArrayList: an array that grows

Example
You can edit this code.
  • add at the end: O(1) on average; get(i): O(1)
  • add(0, x), remove(0), contains: O(n)
  • Lists hold objects, so int becomes Integer (autoboxing)

Strings are immutable

Example
You can edit this code.

StringBuilder for building text

Each + on strings in a loop makes a new string - O(n²) overall. StringBuilder appends in place:

Example
You can edit this code.

Counting characters

Example
You can edit this code.
Key points
  • ArrayList grows automatically; add at end is fast.
  • Compare strings with equals.
  • Use StringBuilder to build strings in loops.

📝 Test yourself

1. Why use StringBuilder in a loop?
2. How should you compare two Strings' text?
3. Fill in the ArrayList method that returns the number of items:
cart.()