String Methods
- Use core String methods: `length`, `substring`, `indexOf`, and `equals`
- Compare Strings correctly with `.equals` rather than `==`
- Predict the result of substring and index operations by counting positions
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.
Trace this code: String s = "computer"; then System.out.println(s.substring(3));
- 1.Number the characters from 0: c(0) o(1) m(2) p(3) u(4) t(5) e(6) r(7).
- 2.
substring(3)with a single argument returns everything from index 3 to the end of the string. - 3.From index 3 onward the characters are p, u, t, e, r, forming
"puter".
puter — the string from index 3 through the end.What does this print? `String a = "cat";` then `String b = "hat";` then `System.out.println(a.equals(b));`
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.
What does this print? `String s = "computer";` then `System.out.println(s.substring(3));`
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