---
title: "String Objects, Immutability, and Concatenation | FiveStudy"
description: "Strings never change — operations give birth. What looks like change is rebirth."
url: https://fivestudy.com/guides/string-immutability-concatenation
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# String Objects, Immutability, and Concatenation

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Using Objects and Methods

AP® Computer Science A · Using Objects and Methods

# String Objects, Immutability, and *Concatenation*

How String objects are created, why they can never be changed once made, and exactly what + and += produce when strings are combined with other strings, numbers, booleans, and objects.

1. String Objects 2. Immutability 3. Concatenation 4. Left-to-Right Evaluation 5. Primitives Become Text 6. Objects Become Text

Big Picture

A `String` object represents a sequence of characters. It can be created with a string literal or by calling the `String` class constructor, and the class is part of `java.lang`, so it is available by default. Strings are **immutable**: once a `String` object is created, its characters cannot be changed, and methods called on it never change its content. Combining strings with `+` or `+=` always produces a *new* `String` object, and any primitive or object joined to a string is converted to text automatically.

## 1 String Objects

Text in Java is stored in objects of the `String` class. A `String` object represents a sequence of characters: letters, digits, spaces, and punctuation, in order. The most common way to create one is a **string literal**, text in double quotation marks, such as `"maple"`. A string can also be created by calling the `String` class constructor, as in `new String("maple")`, which builds a new object with the same characters.

The `String` class is part of the `java.lang` package, and classes in `java.lang` are available by default, so no `import` is ever needed. Because `String` is a class, string variables are reference variables: they hold a reference to a `String` object, can be `null`, and are compared for equal characters with `equals` rather than `==`.

**Figure 1.** A `String` object represents a sequence of characters and can be created by using a string literal or by calling the `String` class constructor.

| Fact | Meaning | Example |
| --- | --- | --- |
| Sequence of characters | A String holds characters in order | `"maple"` has 5 |
| Two ways to create | A literal, or the String constructor | `"maple"`, `new String("maple")` |
| In java.lang | Available without an import | `String s;` works in any class |
| Immutable | Once created, its characters cannot change | `s.substring(1)` leaves `s` unchanged |

Worked Example 1 Creating strings

### Literal or Constructor

Predict the output.

Code

```
String a = "maple";
String b = new String("maple");
String c = "";
System.out.println(a.length() + " " + b.length() + " " + c.length());
System.out.println(a.equals(b));
System.out.println("[" + c + "]");
```

Output

```
5 5 0
true
[]
```

1. 1 **`a`** is created from a literal and `b` from the constructor; both hold the five characters of "maple".
2. 2 **`c`** is the empty string literal: a real `String` object with length 0.
3. 3 **`a.equals(b)`** compares characters: `true`.
4. 4 **Printing `c`** between brackets shows nothing between them.

**Result:** The output is 5 5 0, true, and []. Literals and constructor calls both produce `String` objects; `equals` compares their characters.

## 2 Strings Are Immutable

A `String` object is **immutable**, meaning once a `String` object is created, its attributes cannot be changed. Methods called on a `String` object do not change the content of the `String` object. `city.substring(0, 3)` does not shorten `city`; it builds and returns a new string containing the first three characters.

Code that appears to change a string actually creates a new one and reassigns the variable. After `word = word + "y";`, the variable `word` refers to a new object, while the original object still holds its old characters. If the result of a string method is not stored, it is lost, and the original variable is exactly as it was.

Immutability makes strings safe to share. When two variables refer to the same `String` object, neither can alter the text the other sees; the only way to "change" one is to reassign it to a new object, which leaves the other variable untouched.

**Figure 2.** A `String` object is immutable: once created, its characters cannot be changed. Operations that seem to change a string create a new one.

Worked Example 2 Immutability

### Methods Do Not Change the String

Predict the output.

Code

```
String city = "Valencia";
city.substring(0, 3);
System.out.println(city);
String part = city.substring(0, 3);
System.out.println(part);
city = city.substring(4);
System.out.println(city);
```

Output

```
Valencia
Val
ncia
```

1. 1 **Line 2** builds the new string "Val" but discards it; `city` is unchanged.
2. 2 **Storing the result.** `part` refers to "Val".
3. 3 **Reassigning `city`.** `city.substring(4)` builds "ncia" and the variable now refers to it. The original "Valencia" object itself was never altered.

**Result:** The output is Valencia, Val, and ncia. Methods called on a `String` do not change its content; to keep a result, store it.

Worked Example 3 Aliases and immutability

### Two Variables Sharing a String

Predict the output.

Code

```
String a = "sun";
String b = a;
a += "set";
System.out.println(a);
System.out.println(b);
```

Output

```
sunset
sun
```

1. 1 **`String b = a;`** makes both variables refer to the same "sun" object.
2. 2 **`a += "set";`** builds a new object "sunset" and reassigns only `a`.
3. 3 **`b`** still refers to the unchanged "sun".

**Result:** The output is sunset, then sun. Because strings cannot be changed, sharing a `String` between variables is always safe.

Common Mistake 1 · Calling a String Method and Ignoring the Result

`name.substring(1);` on a line by itself does nothing useful: the new string is built and discarded, and `name` is unchanged. Store the result, either in a new variable or back in the same one: `name = name.substring(1);`.

## 3 Concatenation With + and +=

Two `String` objects can be concatenated together, or combined, using the `+` or `+=` operator, resulting in a new `String` object. `"rain" + "bow"` produces "rainbow". Neither original string is changed; the result is a third object.

The compound operator works as it does for numbers: `log += "start";` means `log = log + "start";`. Each use builds a new string from the old text and the new piece, then reassigns the variable. Building text this way is common for creating messages, labels, and lists, usually starting from the empty string `""`.

Spaces are characters like any other, and concatenation never adds them for you. `"rain" + "bow"` is "rainbow", and `"Row" + 12` is "Row12". To separate pieces, include the space inside a literal, as in `"Row " + 12`, or join a `" "` between values. Many output mistakes are simply a missing or extra space inside a literal.

| Statement | log refers to | New object created? |
| --- | --- | --- |
| String log = ""; | "" | yes (empty string) |
| log += "start"; | "start" | yes |
| log += 3; | "start3" | yes |
| log += true; | "start3true" | yes |
| log += 2.5; | "start3true2.5" | yes |

Worked Example 4 Compound concatenation

### Building Text With +=

Predict the output.

Code

```
String log = "";
log += "start";
log += 3;
log += true;
log += 2.5;
System.out.println(log);
System.out.println(log.length());
```

Output

```
start3true2.5
13
```

1. 1 **Each `+=`** builds a new `String` from the old text plus the new value, and stores it in `log`.
2. 2 **Conversions.** 3 becomes "3", `true` becomes "true", 2.5 becomes "2.5".
3. 3 **Length.** "start" (5) + "3" (1) + "true" (4) + "2.5" (3) = 13 characters.

**Result:** The output is start3true2.5 and 13. `+=` with a `String` concatenates, converting each primitive to text.

## 4 Left-to-Right Evaluation

When an expression contains several `+` operators, Java evaluates them from left to right, and each one decides on its own whether to add or concatenate. If both operands are numbers, `+` adds. If at least one operand is a `String`, `+` concatenates. So `1 + 2 + "3"` adds first and then joins, giving "33", while `"1" + 2 + 3` joins twice, giving "123".

Operator precedence still applies: `*`, `/`, and `%` are evaluated before `+`, so `"Total: " + qty * price` multiplies first. But an addition you want performed inside a longer message needs parentheses: `"Items: " + (qty + 1)`.

**Figure 3.** `+` works left to right. It adds while both operands are numbers and concatenates as soon as one operand is a `String`.

| Expression | Result | Why |
| --- | --- | --- |
| `1 + 2 + "3"` | `"33"` | Addition first, then concatenation |
| `"1" + 2 + 3` | `"123"` | A String comes first, so both + join |
| `"1" + (2 + 3)` | `"15"` | Parentheses add first |
| `"Total: " + 4 * 2.5` | `"Total: 10.0"` | * before + |
| `"Open: " + true` | `"Open: true"` | boolean converted to text |

Worked Example 5 Order of evaluation

### When + Adds and When It Joins

Predict each line.

Code

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

Output

```
33
123
15
9=45
```

1. 1 **`1 + 2 + "3"`.** Left to right: 1 + 2 = 3 (both numbers), then 3 + "3" = "33".
2. 2 **`"1" + 2 + 3`.** "1" + 2 = "12", then "12" + 3 = "123".
3. 3 **Parentheses first.** 2 + 3 = 5, then "1" + 5 = "15".
4. 4 **Mixed.** 4 + 5 = 9, then "9=", then "9=4", then "9=45". After the first `String` appears, every later `+` concatenates.

**Result:** The output is 33, 123, 15, and 9=45. `+` is evaluated left to right; use parentheses when you want arithmetic inside a longer concatenation.

Worked Example 6 Operator precedence

### Multiplication Before Concatenation

Predict the output.

Code

```
int qty = 4;
double price = 2.5;
System.out.println("Total: " + qty * price);
System.out.println("Items: " + qty + 1);
System.out.println("Items: " + (qty + 1));
```

Output

```
Total: 10.0
Items: 41
Items: 5
```

1. 1 **Line 1.** `*` has higher precedence than `+`, so `qty * price` = 10.0 is computed first, then joined: "Total: 10.0".
2. 2 **Line 2.** `+` operators run left to right: "Items: " + 4 = "Items: 4", then + 1 = "Items: 41".
3. 3 **Line 3.** Parentheses force the addition first: 5.

**Result:** The output is Total: 10.0, Items: 41, and Items: 5. Multiplication and division happen before `+`; addition inside a concatenation needs parentheses.

Common Mistake 2 · Expecting Addition Inside a Message

`"Sum: " + 4 + 5` produces "Sum: 45", not "Sum: 9", because the first `+` already produced a `String`. Write `"Sum: " + (4 + 5)` to add first.

## 5 Primitive Values Become Text

A primitive value can be concatenated with a `String` object. This causes the implicit conversion of the primitive value to a `String` object. An `int` such as 12 becomes "12", a `double` such as 9.5 becomes "9.5", and a `boolean` becomes "true" or "false". The conversion happens automatically; no method call is needed.

The text produced for a `double` always includes a decimal point, so 10.0 appears as "10.0", never "10". Values with round-off error appear with all their digits, exactly as `System.out.println` would print them, which is worth remembering when predicting the output of messages built from calculations.

The conversion applies only to the operand that is not a `String`, and only at the moment that `+` is evaluated. The original variable keeps its type: after `String msg = "Row " + row;`, the variable `row` is still an `int` and can still be used in arithmetic. Only the new string contains its digits as text.

**Figure 4.** A primitive value concatenated with a `String` is implicitly converted to text. An object is converted by its `toString` method.

Common Mistake 3 · Forgetting That double Results Print With a Decimal

`"Total: " + 4 * 2.5` is "Total: 10.0". Whenever a `double` is joined to a string, its text form includes the decimal point and fractional part, even when the value is a whole number.

## 6 Objects Become Text

A `String` object can be concatenated with any object, which implicitly calls the object's `toString` method. This behavior is guaranteed to exist because every class has an inheritance relationship with the `Object` class, which provides a `toString` method. An object's `toString` method returns a string value representing the object.

The version from `Object` returns the class name, an `@` sign, and a code that differs between runs, which is rarely useful to a reader. Subclasses of `Object` often override the `toString` method with a class-specific implementation; **method overriding** occurs when a public method in a subclass has the same method signature as a public method in the superclass, but its behavior is specific to the subclass. When a class you are using does not provide a helpful text form, build the message from its getter methods instead.

Worked Example 7 Concatenating objects

### What an Object Becomes in a String

A `Plant` object is joined to a string. The class does not define its own text form, so the version inherited from `Object` is used: the class name, an `@`, and a code that varies from run to run. Predict the output.

A small Plant class and a short program

```
public class Plant
{
    private String name;

    public Plant(String n)
    {
        name = n;
    }

    public String getName()
    {
        return name;
    }
}
```

Output

```
Plant: Plant@
12
Plant: fern
```

1. 1 **`"Plant: " + p`** implicitly calls the object's `toString` method. Every class has one, guaranteed by its relationship with `Object`.
2. 2 **The inherited version** returns the class name, `@`, and a code. The first 13 characters are "Plant: Plant@", and the `@` is at index 12.
3. 3 **Useful text.** To show the plant's name, call a method that returns it: "Plant: fern".

**Result:** The output is Plant: Plant@, 12, and Plant: fern. Concatenating an object calls its `toString` method; classes often replace it with their own version, but this one relies on the one from `Object`.

Common Mistake 4 · Expecting an Object to Print Its Data

Joining an object to a string does not list its attributes unless its class provides that behavior. With the version inherited from `Object`, the result looks like "Plant@" followed by a code. Use the object's methods, such as `p.getName()`, to put its data into a message.

### Four Habits for Strings

#### 1. Strings Never Change

Methods and + build new strings; store the result.

#### 2. Read + Left to Right

Numbers add until a String appears; then everything joins.

#### 3. Parenthesize Arithmetic

Put additions inside messages in parentheses.

#### 4. Objects Use toString

Joining an object calls its toString method.

Core Synthesis

A `String` object represents a sequence of characters and can be created by using a string literal or by calling the `String` class constructor; the class is part of `java.lang` and available by default. A `String` object is immutable, so methods called on it do not change its content. Two `String` objects can be concatenated with `+` or `+=`, resulting in a new `String` object; a primitive value concatenated with a `String` is implicitly converted to a `String`, and concatenating any object implicitly calls its `toString` method, which every class has through its relationship with `Object`.

FiveStudy AP® Computer Science A Study Guide · Using Objects and Methods · String Objects, Immutability, and Concatenation Back to top ↑
