String Methods
IB Syllabus: B2.1.2 — Construct programs that can extract and manipulate substrings.
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);
Practice Exercises
Core
-
Domain extractor - Read a URL like
"www.google.com"and extract just"google". -
Replace first character - Read a word, replace the first letter with
'X'(usesubstring()to rebuild the string). -
File extension extractor - Read a file name from the user (e.g.,
"MyClass.java"). Extract and output the file extension. Strategy:indexOf(".")to find the dot,substring(dotIndex + 1)to extract the extension. Think about: what should happen if there is no dot?
Extension
-
Word count - Count words in a sentence (
count spaces + 1). -
Palindrome checker - Check if a word reads the same forwards and backwards using
charAt(). -
Initials method - Wrap your initials code in a
public static String getInitials(String fullName)method.
Challenge
-
Caesar cipher - Shift each character by N positions using
charAt()and type casting. -
Title case - Convert
"hello world from java"to"Hello World From Java".
Exam-Style (15 marks)
Student record parser - Given strings in the format "LastName, FirstName (ID)":
- (a) Extract the last name [3 marks]
- (b) Extract the first name [3 marks]
- (c) Extract the ID (without parentheses) [3 marks]
- (d) Write a method that takes a
String[]of such records and returns a count of records with a given last name [5/6 marks]
GitHub Classroom
Codespace Setup Instructions (click to expand)
First Time Setup
- Click “Open in GitHub” above, then click the green “Accept this assignment” button
- Check the email registered with your GitHub account – click the link there to open your repository. This avoids access issues and means your teacher does not need to share links manually
- Wait for your repository to be created, then click “Open in Codespace”
- Wait for the Codespace to finish loading (you’ll see VS Code in your browser)
Important: Switch to Standard Mode
- Look at the bottom status bar. If it says
Java: Lightweight Mode, click on it and select Standard - Wait for Java to finish loading (status bar will say
Java: Ready) - Without Standard Mode, the Run button won’t work and you’ll get “Main method not found” errors
Dismiss Popups
You’ll see two notification popups. Dismiss them both:
- “Would you like VS Code to periodically run git fetch?” → Click No
- “There’s a pull request associated with main” → Click Don’t Show Again
These are housekeeping popups, not part of the assignment.
How to Code
- Open
src/StringMethods.java. This is the only file you need to edit - Complete each
// TODOsection - Click the Run button (▶ above
main) to test your output - Compare your output with the expected output written in the comments above each task
How to Check Your Code
You can check your work in two ways:
Option A: Run your code directly
- Click the Run button (▶) above
maininStringMethods.java - Compare your printed output with the expected output shown in the comments above each task
Option B: Run the autograder tests
- Open the Terminal (Menu → Terminal → New Terminal)
- Type
bash run-tests.shand press Enter - Green ✓ = test passed, Red ✗ = test failed
- Each test tells you what it expected. Read the error message to fix your code
How to Submit
- Click the Source Control icon (branch icon) in the left sidebar
- Type a message like
completed tasksin the message box - Click the green Commit button
- If asked “stage all changes?” → click Always
- Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
- Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard
How to Review Feedback
- Go to your repository on GitHub
- Click the “Pull requests” tab at the top
- Open the pull request called “Feedback”
- Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
- Read through each comment carefully, then fix your code in Codespaces
- Run
bash run-tests.shin your Codespaces Terminal to check your fixes - Commit and push again (repeat steps 12-17). The autograder will re-run automatically
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