String Methods
IB Syllabus: B2.1.2 — Extract and manipulate substrings using String methods.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Code Check
- Trace Exercise
- Trace Exercise 2 — Parsing
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- Connections
Key Concepts
String is not a primitive type — it is an object with built-in methods. Strings are immutable: every method returns a new String without changing the original.
Quick Reference
| Method | What it returns | Example |
|---|---|---|
.length() | Number of characters | "Hi".length() → 2 |
.charAt(i) | The char at index i | "Hi".charAt(1) → 'i' |
.substring(s) | From index s to end | "Hello".substring(2) → "llo" |
.substring(s, e) | From s up to (not incl.) e | "Hello".substring(1, 4) → "ell" |
.indexOf(str) | Start index of str, or -1 | "Hello".indexOf("ll") → 2 |
.toUpperCase() | All uppercase | "hi".toUpperCase() → "HI" |
.toLowerCase() | All lowercase | "HI".toLowerCase() → "hi" |
.equals(str) | True if content matches | "a".equals("a") → true |
.equalsIgnoreCase(str) | Matches ignoring case | "A".equalsIgnoreCase("a") → true |
.compareTo(str) | Negative / 0 / positive | "a".compareTo("b") → negative |
Common exam trap:
substring(start, end)returns characters fromstartup to but not includingend."Hello".substring(1, 4)gives"ell"(indices 1, 2, 3) — index 4 is excluded.
Always compare Strings with
.equals(), never==. The==operator compares memory references, not content.
Worked Examples
Example 1: Basic String Methods
String name = "Hello, World!";
System.out.println(name.length()); // 13
System.out.println(name.charAt(0)); // 'H'
System.out.println(name.charAt(7)); // 'W'
System.out.println(name.substring(7)); // "World!"
System.out.println(name.substring(7, 12)); // "World"
System.out.println(name.indexOf("World")); // 7
System.out.println(name.indexOf("Java")); // -1
System.out.println(name.toUpperCase()); // "HELLO, WORLD!"
System.out.println(name.toLowerCase()); // "hello, world!"
Key points:
- Indices start at 0, not 1
.length()uses parentheses (it’s a method call) — compare with array.lengthwhich has no parentheses.indexOf()returns -1 if the substring is not found
Example 2: Parsing a Full Name
String fullName = "Alice Johnson";
int spaceIndex = fullName.indexOf(" "); // 5
String firstName = fullName.substring(0, spaceIndex); // "Alice"
String lastName = fullName.substring(spaceIndex + 1); // "Johnson"
System.out.println("First: " + firstName);
System.out.println("Last: " + lastName);
System.out.println("Total characters: " + fullName.length()); // 13
Pattern: Find a delimiter with indexOf(), then split with substring().
Example 3: Comparing Strings
String s1 = "apple";
String s2 = "apple";
String s3 = "APPLE";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false (case matters)
System.out.println(s1.equalsIgnoreCase(s3)); // true
System.out.println("apple".compareTo("banana")); // negative (a < b)
System.out.println("cat".compareTo("cat")); // 0 (equal)
System.out.println("dog".compareTo("cat")); // positive (d > c)
compareTo() returns:
- Negative → first string comes before alphabetically
- Zero → strings are equal
- Positive → first string comes after alphabetically
Example 4: Building Strings Character by Character
String word = "Hello";
String reversed = "";
for (int i = word.length() - 1; i >= 0; i--) {
reversed = reversed + word.charAt(i);
}
System.out.println(reversed); // "olleH"
This pattern — iterating through characters with
charAt()— is very common in IB Paper 2 questions.
Example 5: Counting Characters
String sentence = "The quick brown fox";
int spaceCount = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ') {
spaceCount++;
}
}
System.out.println("Spaces: " + spaceCount); // 3
Notice
== ' 'with single quotes — we are comparingcharvalues (primitives), so==is correct here. Only use.equals()for String objects.
Quick Code Check
Q1. What does "Hello".substring(1, 4) return?
Q2. What does "Hello".indexOf("lo") return?
Q3. What does "Hello".indexOf("xyz") return?
Q4. After running this code, what is word?String word = "hello"; word.toUpperCase();
Q5. Which is correct for getting the length of a String?
Trace Exercise
Trace this code — fill in the value of each variable.
String word = "Computer";
int len = word.length();
char first = word.charAt(0);
String sub = word.substring(3, 7);
String upper = word.toUpperCase();
Hint: C=0, o=1, m=2, p=3, u=4, t=5, e=6, r=7
| Line | Variable | Value |
|---|---|---|
word.length() | len | |
word.charAt(0) | first | |
word.substring(3, 7) | sub | |
word.toUpperCase() | upper |
Trace Exercise 2 — Parsing
Trace this code — work out the values step by step.
String email = "alice@school.edu";
int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);
String domain = email.substring(atIndex + 1);
int dotIndex = domain.indexOf(".");
String extension = domain.substring(dotIndex + 1);
| Variable | Value |
|---|---|
atIndex | |
username | |
domain | |
dotIndex | |
extension |
Code Completion
This exercise practises the common pattern of splitting a string at a delimiter — use indexOf() to find the space, then substring() to extract the parts before and after it. Complete the code to extract the first name and last name from a full name.
String fullName = "John Smith";
int space = fullName.;
String first = fullName.;
String last = fullName.substring();
System.out.println("First: " + first); // John
System.out.println("Last: " + last); // Smith Spot the Bug
This code should check if two strings have the same content using an if statement, but it uses the wrong comparison operator. This is one of the most common Java mistakes on IB exams. Find the bug.
String input = "hello";
String expected = "hello";
if (input == expected) {
System.out.println("Match!");
}What is wrong and how do you fix it?
This code should use charAt() to print the last character of a word, but it crashes with a StringIndexOutOfBoundsException. The bug tests your understanding of zero-based indexing. Find it.
String word = "Java";
char last = word.charAt(word.length());
System.out.println("Last char: " + last);What is wrong and how do you fix it?
Output Prediction
This code demonstrates three core String methods — substring(), charAt(), and indexOf() — applied to the same string. Trace through each call carefully, remembering that indices start at 0 and substring(start, end) excludes the end index.
What does this code print?
String s = "Programming";
System.out.println(s.substring(0, 7));
System.out.println(s.charAt(3));
System.out.println(s.indexOf("gram"));
Program
g
3This code builds a new string by iterating through the characters of the original string in reverse order using charAt(). This is a classic string-reversal algorithm that combines loop traversal with string concatenation.
What does this code print?
String word = "Hello";
String result = "";
for (int i = word.length() - 1; i >= 0; i--) {
result = result + word.charAt(i);
}
System.out.println(result);
olleHPractice Exercises
Core
-
String length — Read a word from the user and print how many characters it has.
-
First and last — Read a word and print its first and last characters.
-
Initials — Read a first name and last name (separated by a space). Print the initials (e.g., “Alice Johnson” → “A.J.”).
-
Substring extractor — Read a word, a start index, and an end index. Print the substring.
Extension
-
Word count — Read a sentence and count how many words it contains (hint: count spaces and add 1).
-
Email parser — Read an email address like
"alice@school.edu"and print the username and domain separately. -
Palindrome checker — Read a word and check if it reads the same forwards and backwards (e.g., “racecar”). Use a loop with
charAt().
Challenge
-
Caesar cipher — Read a word and a shift value. Shift each character by that many positions in the alphabet (e.g., ‘A’ with shift 3 → ‘D’). Use
charAt()and type casting. -
Title case — Read a sentence and convert it to title case (first letter of each word uppercase, rest lowercase).
GitHub Classroom
Connections
Prerequisites:
- Variables & Data Types — understanding String as a type
Related Topics:
- Iteration — loops for traversing Strings character by character
- 1D Arrays — similar index-based access pattern
What’s Next:
- Exception Handling — what happens when String operations fail
- Selection — using String comparisons in conditions