AP® Computer Science A · Unit 1 · Topic 1.15

Strings, Immutability, substring, and indexOf

A String in Java never changes once created. Methods like substring and indexOf don't edit the original string — they read it and hand back new information.

Strings are immutable: once "HELLO" exists in memory, it exists forever as "HELLO". Nothing you call on it edits its characters. When you write s = s.substring(1), Java builds a brand new String object from the pieces you asked for, then points s at that new object. The old String is still sitting on the heap, now with nothing pointing at it. This matters because it means every String method is really a question, not a command — it returns an answer, it never mutates the original.

substring(start, end) carves out characters starting at index start, which counts, up to but not including index end, which doesn't. That's why the length of the result is always end minus start. "COMPUTER".substring(3, 6) starts at index 3 (the 'P') and stops before index 6 (the 'T'), giving "PUT". With one argument, substring(start) just grabs everything from start to the end of the string. indexOf works similarly but searches: it scans left to right and returns the index where the first match begins — not every place it could match.

This immutability is the same idea you meet with references elsewhere in the unit: a variable holding a String is really holding a reference to an object, and reassigning that variable just points it somewhere new. Concatenating in a loop makes this expensive — each += quietly builds a fresh String and discards the old one, which is why StringBuilder shows up later for heavy string work.

Key terms

Immutable
Once created, the object's contents can never be changed.
substring(start, end)
Returns the characters from index start up to, but not including, index end.
indexOf
Returns the index where the first occurrence of a target string begins, searching left to right.
Heap
The region of memory where objects, including Strings, actually live.

Watch it explained

  1. How it worksHow does substring carve out a piece using a start that counts and an end that does not?
  2. Worked exampleFind what "COMPUTER".substring(3, 6) returns, with the indices marked underneath.
  3. Worked exampleFind what "banana".indexOf("na") returns and why the answer is not 4.
  4. How it worksHow does concatenating inside a loop leave a trail of discarded String objects behind?
  5. Common mistakeWhy doesn't s.substring(1) change the string that s was already pointing at?

Check yourself

Your turn1 of 2
String s = "ABCDEFGHIJ"; How many characters does s.substring(2, 8) return?

End of topic.