Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- A
Stringobject represents a sequence of characters. It is created with a string literal or by calling theStringconstructor. The class is injava.lang, so it is available by default. - A
Stringis immutable: once created, its attributes cannot be changed. Methods called on it do not change its content. +and+=concatenate and produce a newString. A primitive concatenated with aStringis implicitly converted to aString. AStringconcatenated with any object implicitly calls that object’stoStringmethod.- A
Stringhas indices from 0 to one less than its length. Using an index outside the range throws aStringIndexOutOfBoundsException. substring(index, index + 1)is a one-character string.
Key relationships
| Method | Result for "microscope" (length 10) |
|---|---|
length() |
10 |
substring(2, 6) |
"cros" (indices 2 to 5) |
substring(6) |
"cope" |
substring(0, 1) |
"m" |
substring(10) |
"" (legal) |
indexOf("sco") |
5 |
indexOf("z") |
-1 |
equals("microscope") |
true |
compareTo("microscope") |
0 |
| Expression | Value |
|---|---|
"a" + 1 + 2 |
"a12" |
1 + 2 + "a" |
"3a" |
"a" + (1 + 2) |
"a3" |
"x" + 2.5 + true |
"x2.5true" |
"apple".compareTo("banana") |
negative |
"banana".compareTo("apple") |
positive |
Five steps for a string question
- Write the string with its indices under every character (spaces count).
- For
substring(from, to)markfromand the character just beforeto. - Use
indexOfto find positions instead of counting. - Remember immutability: an unstored result is lost; a reassignment makes a new string.
- Check
0 <= from <= to <= length(); otherwise the answer is aStringIndexOutOfBoundsException.
To “change” one letter, build a new string from the parts around it: s.substring(0, 3) + "x" + s.substring(4).
Assumptions and conventions
substring(from, to)includes the character atfromand excludes the one atto.compareTois guaranteed only in its sign: below 0, zero or above 0.- Compare string contents with
equals, not==. - A
Stringvariable that holdsnullcauses aNullPointerExceptionwhen a method is called on it. - A string identical to the single character at
indexissubstring(index, index + 1).
Mistakes to avoid
- Calling
word.substring(1);and expectingwordto change. Store the result. - Off-by-one errors with
substring(from, to): forgetting thattois excluded. - Using index
length()for a character (the last index islength() - 1). - Misreading
"a" + 1 + 2. Work left to right. - Treating
-1fromindexOfas an index. - Comparing strings with
==. - Expecting a particular value from
compareToinstead of its sign.
Quick self-check
- What is
"banana".substring(1, 4)? ("ana") - What is
"banana".indexOf("na")? (2) - What does
3 + 4 + "x"evaluate to? ("7x") - What happens with
"abc".substring(1, 5)? (StringIndexOutOfBoundsException) - After
String s = "go"; s += "al";what doessrefer to? (A new string,"goal".)
Next: practice questions.