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

A String object cannot be modified in place. substring returns a String value while leaving the original contents unchanged, and concatenation also leaves the original objects unchanged. Assigning a result changes which String a variable refers to; it does not edit the old object. equals compares character sequences, while == compares references. Two distinct String objects can therefore have equal contents.

Use a returned value in an assignment, return statement, condition, or other expression. To replace a variable's text, assign the String result to that variable.

Common error

Calling s.substring(1); alone discards the result. Assigning s = s.substring(1); changes s's reference while leaving the original object unchanged.

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