String Methods

IB Syllabus: B2.1.2 — Construct programs that can extract and manipulate substrings.

Table of Contents

  1. Key Concepts
    1. Quick Reference
  2. Worked Examples
    1. Example 1: Basic String Methods
    2. Example 2: Parsing a Full Name
    3. Example 3: Comparing Strings
    4. Example 4: Building Strings Character by Character
    5. Example 5: Counting Characters
  3. Quick Code Check
  4. Trace Exercise
  5. Trace Exercise 2 - Parsing
  6. Code Completion
  7. Spot the Bug
  8. Output Prediction
  9. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
    4. Exam-Style (15 marks)
  10. GitHub Classroom
  11. 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 from start up to but not including end. "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 .length which 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 comparing char values (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

LineVariableValue
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);
VariableValue
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"));
Expected: Program
g
3

This 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

  1. Domain extractor - Read a URL like "www.google.com" and extract just "google".

  2. Replace first character - Read a word, replace the first letter with 'X' (use substring() to rebuild the string).

  3. 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

  1. Word count - Count words in a sentence (count spaces + 1).

  2. Palindrome checker - Check if a word reads the same forwards and backwards using charAt().

  3. Initials method - Wrap your initials code in a public static String getInitials(String fullName) method.

Challenge

  1. Caesar cipher - Shift each character by N positions using charAt() and type casting.

  2. 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

String Methods
Practice using length(), charAt(), substring(), indexOf(), and String comparison.
Codespace Setup Instructions (click to expand)

First Time Setup

  1. Click “Open in GitHub” above, then click the green “Accept this assignment” button
  2. 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
  3. Wait for your repository to be created, then click “Open in Codespace”
  4. Wait for the Codespace to finish loading (you’ll see VS Code in your browser)

Important: Switch to Standard Mode

  1. Look at the bottom status bar. If it says Java: Lightweight Mode, click on it and select Standard
  2. Wait for Java to finish loading (status bar will say Java: Ready)
  3. 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

  1. Open src/StringMethods.java. This is the only file you need to edit
  2. Complete each // TODO section
  3. Click the Run button (▶ above main) to test your output
  4. 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 main in StringMethods.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.sh and 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

  1. Click the Source Control icon (branch icon) in the left sidebar
  2. Type a message like completed tasks in the message box
  3. Click the green Commit button
  4. If asked “stage all changes?” → click Always
  5. Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
  6. Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard

How to Review Feedback

  1. Go to your repository on GitHub
  2. Click the “Pull requests” tab at the top
  3. Open the pull request called “Feedback”
  4. Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
  5. Read through each comment carefully, then fix your code in Codespaces
  6. Run bash run-tests.sh in your Codespaces Terminal to check your fixes
  7. Commit and push again (repeat steps 12-17). The autograder will re-run automatically

Connections

Prerequisites:

Related Topics:

  • Iteration - loops for traversing Strings character by character
  • 1D Arrays - similar index-based access pattern

What’s Next:


© EduCS.me — A resource hub for Computer Science education

This site uses Just the Docs, a documentation theme for Jekyll.