Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

4.3: String Immutability

String methods return values without changing the original object. Assign the result when a transformation should replace a variable's current value.

College Board Unit 1

How it works

Strings in Java cannot be modified in place. Methods such as substring, toUpperCase, and replace return a brand-new String and leave the original untouched. A variable only changes when you assign the result back to it. Comparison follows the same object logic: equals compares character content, while == compares references and can be false for two Strings with identical text.

Assign the result of every String operation, or it has no effect.

Common error

Calling a method and expecting the variable to change, which silently does nothing.

Worked example

Java

String text = "plane";
text.substring(1);
System.out.println(text);
text = text.substring(1);
System.out.println(text);

Output

plane
lane

The first result is discarded. The assignment makes text refer to the returned String.

Exercises

4.3.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

String a = "cat";
String b = a;
a += "s";
System.out.println(a + ":" + b);
Show solution

Output

cats:cat

Reassigning a does not change the immutable object still referenced by b.

4.3.2 · Write code

Given String word = "book" and String saved = word, replace word with its last three characters followed by "!". Print word and saved, separated by a colon.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

String word = "book";
String saved = word;
word = word.substring(1) + "!";
System.out.println(word + ":" + saved);
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic