← Back to course

String Methods

You’ll be able to

The String toolkit

Strings come with a standard toolkit. length() gives the character count; substring(a, b) extracts a slice; indexOf(str) returns the first index where str appears, or -1 if it never does; and equals(other) reports whether two strings contain the same characters. Positions are zero-based: the first character sits at index 0, the last at index length() - 1.

Comparing strings: == vs .equals

For objects, == asks whether two references point to the same object, not whether they hold the same text. To compare the contents of two strings you must use a.equals(b). Relying on == for strings is one of the most common Java bugs, because two different String objects can hold identical characters yet fail an == test.

indexOf
s.indexOf(t) → first index where t begins, or −1 if absent
Searching left to right, it reports the position of the first match. A return of −1 means the substring is not present.
Worked example

Trace this code: String s = "computer"; then System.out.println(s.substring(3));

  1. 1.Number the characters from 0: c(0) o(1) m(2) p(3) u(4) t(5) e(6) r(7).
  2. 2.substring(3) with a single argument returns everything from index 3 to the end of the string.
  3. 3.From index 3 onward the characters are p, u, t, e, r, forming "puter".
Answer: It prints puter — the string from index 3 through the end.
Checkpoint

What does this print? `String a = "cat";` then `String b = "hat";` then `System.out.println(a.equals(b));`

Watch out

Never compare string contents with ==. Use a.equals(b) for value comparison. == tests reference identity and can give surprising results even when the visible text matches.

Checkpoint

What does this print? `String s = "computer";` then `System.out.println(s.substring(3));`

On the exam

For any indexOf or substring question, write the string out and label each character with its index starting at 0. Counting on paper prevents off-by-one mistakes with the excluded end index.

Answer the 2 checkpoints as you read.

Sign in to save your progress