Side Effects &
Immutability
Learn why predictable code depends on controlling what changes and what stays constant: the foundations of side effects and immutable objects in Java.
What Is a Side Effect?
A side effect occurs when a method changes something outside its own scope: modifying a field, updating a global variable, printing to the console, or writing to a file. The method does more than just compute and return a value.
Seeing Side Effects in Action
Why Side Effects Matter
What Is Immutability?
An immutable object cannot be changed after it is created. Once constructed, its state is fixed forever. Java's String class is the most familiar example: calling .toUpperCase() returns a new String rather than modifying the original.
The Core Rule of Immutability
final so it cannot be subclassed.private final.Mutable vs Immutable
| Mutable | Immutable | |
|---|---|---|
| State after creation | Can be changed | Fixed forever |
| Java example | StringBuilder | String |
| Thread safety | Needs synchronization | Inherently safe |
| Side-effect risk | High: any reference can mutate | None: no mutation possible |
| Performance trade-off | Faster in-place updates | Creates new objects |
How to Apply These Ideas
final fields and return new objects instead of modifying existing ones.new ArrayList<>(list) instead of the original reference.saveToFile, not getData).Example 1: Spotting a Side Effect
Example 2: Building an Immutable Class
Example 3: Defensive Copies
The Aliasing Problem
Java's String Is Immutable
Common Mistakes
this.list directly from a getter lets callers mutate your "immutable" object.getValue() that also logs, increments, or modifies state surprises callers.Summary at a Glance
| Concept | Definition | Java Example |
|---|---|---|
| Side effect | Observable change beyond return value | list.add(x) |
| Pure function | No side effects, deterministic | Math.max(a, b) |
| Immutable object | State cannot change after creation | String, Integer |
| Mutable object | State can be modified | ArrayList, StringBuilder |
| Defensive copy | Copy in constructor & getter | new ArrayList<>(list) |
Question 1 of 5
Which of the following is a side effect?
Question 2 of 5
Which Java class is immutable?
toUpperCase() return a new String rather than modifying the original. ArrayList, StringBuilder, and HashMap are all mutable.Question 3 of 5
Consider this class:
public final class Config {
private final List<String> flags;
public Config(List<String> flags) {
this.flags = flags;
}
public List<String> getFlags() {
return flags;
}
}
What is the main flaw in this "immutable" class?
Question 4 of 5
A pure function in Java:
static, can have parameters, and must return a value (not void).Question 5 of 5
Given String s = "abc"; and String t = s;, what happens when you call t.toUpperCase()?
toUpperCase() creates and returns a new String. Because the return value isn't assigned to any variable, both s and t still reference the original "abc".