Unit 1.15: String Manipulation
AP Computer Science A
Learning Objectives
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.
What is a String?
A String object represents a sequence of characters.
Creating Strings
Key Facts
- The String class is part of java.lang package
- Classes in java.lang are available by default (no import needed)
- Strings are immutable - once created, they cannot be changed
String Immutability
Strings are immutable - methods called on a String do not change the original String object.
Important: String methods return NEW String objects rather than modifying the original.
String Concatenation
Strings can be combined using the + or += operator.
Key Points
- Concatenation creates a new String object
- Primitive values are implicitly converted to Strings
- Any object can be concatenated (calls toString() method)
String Indexing
Strings use zero-based indexing: indices range from 0 to length() - 1
Warning: Accessing an index outside the range [0, length()-1] results in a StringIndexOutOfBoundsException
String Method: length()
Returns the number of characters in the String.
Common Use
Often used in loops to process each character in a String:
String Method: substring()
Returns the substring from index from to index to - 1
Returns substring from index from to the end
String Method: indexOf()
Returns the index of the first occurrence of str. Returns -1 if not found.
Tip: Always check if the return value is -1 before using it as an index!
String Method: equals()
Returns true if this String has the same sequence of characters as other.
Important: Always use equals() to compare String content, not ==
The == operator compares memory references, not content.
String Method: compareTo()
Compares two Strings lexicographically (alphabetically).
- Returns negative value if this < other
- Returns 0 if this equals other
- Returns positive value if this > other
Use case: Sorting Strings alphabetically
Practice Problems
Problem 1: What is the output?
Answers: 11, "Program", 3
Problem 2: What is the output?
Answers: negative number, false
Problem 3: Fix the error
Fix: word = word.toUpperCase();