Unit 1 · 25 min
1.15 String Manipulation
A String is an object holding a sequence of characters, and its methods never change it.
Summary, objectives and course and exam description (CED) codes
A String object is an immutable sequence of characters, created with a string literal or the String constructor. The + and += operators concatenate strings into a new String, converting primitives and calling toString on objects. String methods on the Java Quick Reference (length, substring, indexOf, equals and compareTo) use indices from 0 to length() - 1.
By the end of this session you can
- 1.15.A Develop code to create string objects and determine the result of creating and combining strings.
- 1.15.B Develop code to call methods on string objects and determine the result of calling these methods.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. Creating String objects
A String object represents a sequence of characters. You can create one with a string literal or by calling the String class constructor 1.15.A.1.
The String class is part of the java.lang package, and classes in java.lang are available by default 1.15.A.2, so no import is needed.
String team = "Falcons"; // string literal
String city = new String("Porto"); // String constructor
System.out.println(team + " of " + city);
Output:
Falcons of Porto
2. Strings are immutable
A String object is immutable: after it is made, nothing about it can change, and calling a method on it never changes its characters 1.15.A.3. Methods such as substring return a new String; no String method changes the original.
String w = "data";
w.substring(1); // new String made, but not stored
System.out.println(w);
w = w.substring(1); // now w refers to the new String
System.out.println(w);
Output:
data
ata
Watch out: a String method result that is not stored is lost.
3. Concatenation with + and +=
Two String objects can be concatenated (joined) with the + or += operator, which results in a new String object. A primitive value can be concatenated with a String; the primitive is implicitly converted to a String 1.15.A.4. Java works left to right, so where the text first appears matters.
| Code | Value or output | Why |
|---|---|---|
"Score: " + 4 + 5 |
"Score: 45" |
left to right: text first, so 4 and 5 are joined as text |
4 + 5 + " pts" |
"9 pts" |
left to right: 4 + 5 is added first |
w.substring(1); then print w (w is "data") |
data |
the new String was not stored |
w = w.substring(1); then print w |
ata |
now the variable refers to the new String |
System.out.println("Score: " + 4 + 5);
System.out.println(4 + 5 + " pts");
String msg = "Level";
msg += " " + 3;
msg += "!";
System.out.println(msg);
boolean won = true;
System.out.println("Won: " + won);
Output:
Score: 45
9 pts
Level 3!
Won: true
4. Concatenating objects: toString
A String can be concatenated with any object. This implicitly calls the object’s toString method, which returns a string representing the object. Every object has a toString method, because every class is a subclass of Object (topic 1.12) and inherits it 1.15.A.5.
Subclasses of Object often override toString with their own class-specific version. A subclass overrides a method (method overriding) when it writes a public method with the same method signature as a public method of its superclass, so that the method behaves in a way that fits the subclass 1.15.A.5.
Example: p refers to a Plant whose toString method returns "Fern, 30 cm".
Plant p = new Plant("Fern", 30);
System.out.println("Plant: " + p);
p.grow(2);
String label = "Now: " + p;
System.out.println(label);
Output:
Plant: Fern, 30 cm
Now: Fern, 32 cm
Outside the course: writing (overriding) your own toString method. You only need to know that concatenation calls it.
5. Indices and StringIndexOutOfBoundsException
A String has index values from 0 to one less than its length. Attempting to access an index outside this range results in a StringIndexOutOfBoundsException 1.15.B.1. (The to argument of substring may equal length(), because it stops before to. The from argument may also equal length(): "moon".substring(4) is "".)
For String word = "INTERFACE";:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| Character | I | N | T | E | R | F | A | C | E |
length()is 9, so the valid indices are 0 to 8.word.substring(0, 5)is"INTER": it stops BEFORE index 5.word.substring(5)is"FACE": from index 5 to the end.word.substring(2, 3)is"T".
String word = "INTERFACE";
System.out.println(word.substring(0, 5));
System.out.println(word.substring(5));
System.out.println(word.substring(2, 3));
System.out.println("moon".substring(4).length());
System.out.println(word.substring(7, 10));
Output:
INTER
FACE
T
0
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [7, 10) out of bounds for length 9
Index 10 is past the end (the largest allowed to is 9), so the last call throws the exception. The message after the colon can differ between Java versions.
6. The six String methods on the Java Quick Reference
These String methods, what they do and when to use them are part of the Java Quick Reference 1.15.B.2:
| Method | Returns | Example with word = "INTERFACE" |
|---|---|---|
int length() |
the number of characters | word.length() is 9 |
String substring(int from, int to) |
the characters from index from to to - 1 |
word.substring(0, 5) is "INTER" |
String substring(int from) |
substring(from, length()) |
word.substring(5) is "FACE" |
int indexOf(String str) |
the index of the first occurrence of str; -1 if not found |
word.indexOf("FACE") is 5; word.indexOf("X") is -1 |
boolean equals(Object other) |
true if the same sequence of characters, false otherwise |
"Cat".equals("cat") is false |
int compareTo(String other) |
a value < 0 if this comes first alphabetically, 0 if equal, a value > 0 if this comes later | "cat".compareTo("dog") < 0 is true |
Outside the course: using equals to compare a String with an object that is not a String.
String word = "INTERFACE";
System.out.println(word.length());
System.out.println(word.indexOf("FACE"));
System.out.println(word.indexOf("E"));
System.out.println(word.indexOf("X"));
System.out.println("Cat".equals("cat"));
System.out.println("cat".compareTo("dog") < 0);
System.out.println("pear".compareTo("pear"));
System.out.println("plum".compareTo("pear") > 0);
Output:
9
5
3
-1
false
true
0
true
indexOf("E") gives 3, the first E, even though there is another E at index 8.
Watch out: compare String contents with equals, not ==. The == operator checks whether two references point to the same object:
String a = "go";
String b = new String("go");
System.out.println(a.equals(b));
System.out.println(a == b);
Output:
true
false
a and b hold the same characters, but they refer to two different objects.
7. One character, empty strings and null
A string identical to the single character at position index can be created with substring(index, index + 1) 1.15.B.3. The last character is s.substring(s.length() - 1).
String s = "ROBOT";
System.out.println(s.substring(2, 3));
System.out.println(s.substring(s.length() - 1));
int pos = s.indexOf("B");
System.out.println(s.substring(pos, pos + 1));
Output:
B
T
B
Empty string or no string? "" is the empty string: a real String object with length 0, so "".length() is 0, and s.substring(i, i) returns "" for any i from 0 to s.length(). null means no object at all: if s is null, s.length() throws a NullPointerException 1.14.A, 1.15.B.
String empty = "";
System.out.println(empty.length());
System.out.println("ROBOT".substring(3, 3).length());
String none = null;
System.out.println(none.length());
Output:
0
0
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "none" is null
Background (not tested): characters and capitals. Java also has a
chartype ('A') and methods such ascharAtandtoUpperCase.charis outside the course and those methods are not on the Java Quick Reference, so usesubstringin exam answers.compareTocompares character codes, so all capital letters come before lowercase ones:"Zoo".compareTo("apple")is negative. On the exam, strings are “ordered based upon the alphabet”, so most questions use the same case throughout.
System.out.println("Zoo".compareTo("apple") < 0);
Output:
trueLock it in: memory hooks
- substring(from, to)From is in, to is out: count of characters = to - from.
- ImmutableString methods hand you a new string; they never touch the old one. Store it or lose it.
- compareToThink a - b: negative means this comes first, 0 means equal, positive means this comes later.
- One charactersubstring(i, i + 1) is the character at index i.
Common misconceptions
"w.substring(1); changes w."
Not quite. Strings are immutable. substring returns a new String, and if you do not store it, it is lost. Write w = w.substring(1); to keep it.
"substring(from, to) includes the character at index to."
Not quite. It stops BEFORE index to. The number of characters returned is to - from.
"== checks whether two strings have the same characters."
Not quite. == checks whether two references point to the same object. Use equals to compare the characters.
""Score: " + 4 + 5 is "Score: 9"."
Not quite. Java works left to right. "Score: " + 4 is already a String, so 5 is joined as text: "Score: 45".
Exam traps
- substring(from, to) stops BEFORE to. The number of characters returned is to - from.
- Compare String contents with equals, not ==. The == operator checks whether two references point to the same object.
- A String method result that is not stored is lost: w.substring(1); leaves w unchanged.
- Left to right: 1 + 2 + "3" + 4 + 5 is "3345", because 1 + 2 is added before any text appears.
- The to argument of substring may equal length(); an index past that throws a StringIndexOutOfBoundsException.
2PracticeRecall it, then check yourself
In 30 seconds
- A String is an object holding a sequence of characters; create it with a literal or the String constructor. String is in java.lang.
- Strings are immutable: no String method changes the original; methods return a new String.
- + and += concatenate, making a new String; primitives become text, and objects call their toString method.
- Indices run from 0 to length() - 1; a bad index throws a StringIndexOutOfBoundsException.
- Quick Reference methods: length, substring(from, to), substring(from), indexOf, equals, compareTo.
- substring(i, i + 1) gives the single character at index i as a String.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 6 questions
Checkpoint: String Manipulation
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- String methods on the Java Quick Reference (topic 1.15) six methods CED 1.15.B.2
- Ways to create a String object two ways CED 1.15.A.1
- a string literal"hi"
- the String constructor (new String("hi"))
- Operators that concatenate two operators CED 1.15.A.4
- +
- +=
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Stringtap to flip
A class whose objects hold a sequence of characters. String is a reference type in java.lang, and String objects are immutable.
Example and CED codes -
String literaltap to flip
A sequence of characters enclosed in double quotes, such as "Game over".
Example and CED codes -
String concatenationtap to flip
Joining strings with + or +=, which creates a new String. Primitives are converted to text and objects call toString.
Example and CED codes -
Immutabletap to flip
Cannot be changed once created. String objects are immutable: their methods return new strings and never change the original.
Example and CED codes -
Indextap to flip
The position of a character in a String, counted from 0. Valid indices run from 0 to length() - 1.
Example and CED codes -
length()tap to flip
The String method that returns the number of characters in a String.
Example and CED codes -
substringtap to flip
String methods substring(from, to), which returns the characters from index from to to - 1, and substring(from), which goes to the end.
Example and CED codes -
indexOftap to flip
The String method indexOf(String str), which returns the index of the first occurrence of str, or -1 if str is not found.
Example and CED codes -
equalstap to flip
The String method equals(Object other), which returns true if both strings have the same sequence of characters.
Example and CED codes -
compareTotap to flip
The String method compareTo(String other): negative if this comes first alphabetically, 0 if equal, positive if this comes later.
Example and CED codes -
StringIndexOutOfBoundsExceptiontap to flip
The exception thrown when a String method uses an index outside the allowed range.
Example and CED codes -
Method overridingtap to flip
When a public method in a subclass has the same signature as a public method in its superclass but its own behavior.
Example and CED codes -
Object classtap to flip
The class at the top of every Java class hierarchy: all classes are subclasses of Object.
Example and CED codes -
NullPointerExceptiontap to flip
The exception thrown when a method is called on a null reference.
Example and CED codes -
toStringtap to flip
A method that returns a String representing an object; println and string concatenation call it automatically.
Example and CED codes
Questions students ask
What does substring do in Java?
substring(from, to) returns a new String with the characters from index from up to, but not including, index to. substring(from) returns everything from index from to the end.
Why use equals instead of == for strings?
equals compares the sequence of characters. == compares references, so it only tells you whether two variables point to the same String object, which can be false even when the characters match.
What does compareTo return?
A negative value if this string comes before the other alphabetically, zero if they are equal, and a positive value if this string comes after the other.
What does it mean that strings are immutable?
Once a String object is created it cannot change. Methods such as substring return a new String; to keep the result you must store it, for example w = w.substring(1);.
What causes a StringIndexOutOfBoundsException?
Using an index outside the allowed range, for example substring(2, 10) on a 9-character string. Valid character indices run from 0 to length() - 1, and the to argument of substring may also equal length().