# AP® Computer Science A 1.15 String Manipulation

Source: https://lockincs.com/ap-csa/unit-1/1-15-string-manipulation/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 1.15.A, 1.15.A.1, 1.15.A.2, 1.15.A.3, 1.15.A.4, 1.15.A.5, 1.15.B, 1.15.B.1, 1.15.B.2, 1.15.B.3

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.

## What you will learn

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

## 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 `char` type (`'A'`) and methods such as `charAt` and `toUpperCase`. `char` is outside the course and those methods are not on the Java Quick Reference, so use `substring` in exam answers. `compareTo` compares 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:

```
true
```

## Common mix-ups

- Not true: w.substring(1); changes w. 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.
- Not true: substring(from, to) includes the character at index to. It stops BEFORE index to. The number of characters returned is to - from.
- Not true: == checks whether two strings have the same characters. == checks whether two references point to the same object. Use equals to compare the characters.
- Not true: "Score: " + 4 + 5 is "Score: 9". Java works left to right. "Score: " + 4 is already a String, so 5 is joined as text: "Score: 45".

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

## Checkpoint: 6 practice questions

### Question 1

What is printed?

```java
System.out.println(1 + 2 + "3" + 4 + 5);
```

- A. `15`
- B. `3345`
- C. `12345`
- D. `339`

**Answer: B.** Left to right: 1 + 2 is 3; then "3" makes it text: "33", "334", "3345". C joins everything, but 1 + 2 is added before any String appears. D adds 4 + 5, but they are joined as text after the String. A adds all the numbers.

### Question 2

What is printed?

```java
String w = "code";
w.substring(1);
System.out.println(w);
```

- A. `code`
- B. `ode`
- C. `c`
- D. Nothing; a `StringIndexOutOfBoundsException` occurs.

**Answer: A.** Strings are immutable and the new String from `substring` was not stored. B would be printed only after `w = w.substring(1);`. C confuses `substring(1)` with the first character. D is wrong because index 1 is valid for a 4-character string.

### Question 3

What is printed?

```java
String s = "PROGRAMMING";
int g = s.indexOf("G");
int m = s.indexOf("M");
System.out.println(s.substring(g, m + 1));
```

- A. `GRA`
- B. `GRAM`
- C. `GRAMM`
- D. `RAM`

**Answer: B.** `indexOf("G")` is 3 and `indexOf("M")` is 6, so `substring(3, 7)` is "GRAM". A stops before m. C would need the last M. D starts after g.

### Question 4

Assume `str` is a `String` with at least 5 characters. Which expression produces the same result as `str.substring(4)`?

- A. `str.substring(4, str.length() - 1)`
- B. `str.substring(5)`
- C. `str.substring(0, 4)`
- D. `str.substring(4, str.length())`

**Answer: D.** `substring(from)` is defined as `substring(from, length())`. A drops the last character. B starts one character later. C returns the characters before index 4 instead of from index 4.

### Question 5

The code segment below is intended to print `true` when `word1` comes before `word2` alphabetically and `false` otherwise. Assume both are lowercase words that are not equal. Which can replace `/* missing */`?

```java
System.out.println( /* missing */ );
```

- A. `word1.compareTo(word2) > 0`
- B. `word1.compareTo(word2) < 0`
- C. `word1.equals(word2)`
- D. `word2.compareTo(word1) < 0`

**Answer: B.** `compareTo` returns a negative value when `word1` comes first alphabetically. D tests the opposite order (`word2` first). A also tests whether `word1` comes later. C only tests whether the words are equal, which is always false here.

### Question 6

Consider the following code segment. What happens when it is executed?

```java
String code = "AX7";
System.out.println(code.substring(1, 3));
System.out.println(code.substring(2, 4));
```

- A. `X7` on line 1 and `7` on line 2
- B. `AX7` on line 1 and `X7` on line 2
- C. `X7` is printed, then an exception occurs.
- D. Nothing; a `StringIndexOutOfBoundsException` occurs before anything prints.

**Answer: C.** The length is 3, so `substring(1, 3)` is valid and prints X7 (the `to` argument may equal the length). `substring(2, 4)` uses 4, past the length, so a `StringIndexOutOfBoundsException` occurs. A ignores the bad index. B starts at index 0. D is wrong because the first statement runs and prints before the second one fails.

## 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().

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
