01 / 20

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.

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

Pure Function int add(int a, int b) Input a=3, b=5 Output 8 ✓ No external changes Side Effect void addToList(int n) Modifies list field Prints to console

Why Side Effects Matter

✕ Hard to Test
Methods that change global state require complex setup and teardown in every test case.
✕ Hard to Debug
When multiple methods mutate the same object, tracking which one caused a bug is painful.
✕ Surprising Behavior
Callers don't expect a getter to also modify data. Hidden side effects violate the principle of least surprise.

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.

String name = "hello"; String upper = name.toUpperCase(); // name is still "hello" // upper is a new String: "HELLO"

The Core Rule of Immutability

1
Declare the class final so it cannot be subclassed.
2
Make all fields private final.
3
Provide no setter methods (no mutators).
4
If a field references a mutable object (like an array or list), return a defensive copy from getters.
Immutable Object private final String name private final int age Only getters, no setters ✕ set() ✕ mutate() ✓ get() returns copy

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

1
Identify the side effects: Does this method modify a field, print output, or change an argument?
2
Separate concerns: Split computation (pure) from mutation (side effect) into different methods.
3
Prefer immutable data: Use final fields and return new objects instead of modifying existing ones.
4
Defensive copies: When you must expose a mutable field, return new ArrayList<>(list) instead of the original reference.
5
Name honestly: If a method has side effects, its name should make that clear (e.g., saveToFile, not getData).

Example 1: Spotting a Side Effect

public class Counter { private int count = 0; public int getCount() { count++; // Side effect! return count; } }

Example 2: Building an Immutable Class

public final class Point { private final int x; private final int y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public Point translate(int dx, int dy) { return new Point(x + dx, y + dy); // new object } }

Example 3: Defensive Copies

public final class Roster { private final List<String> names; public Roster(List<String> names) { this.names = new ArrayList<>(names); // copy in } public List<String> getNames() { return new ArrayList<>(names); // copy out } }

The Aliasing Problem

listA listB Same ArrayList in memory "A" "B" "C" listB.add("C") changes listA too! List<String> listB = listA; Both variables point to the SAME object

Java's String Is Immutable

String greeting = "Hello"; String shout = greeting.toUpperCase(); System.out.println(greeting); // "Hello" (unchanged) System.out.println(shout); // "HELLO" (new object)
✓ Safe to share
Multiple variables can reference the same String without risk.
✓ Thread safe
No synchronization needed: the object never changes.
★ String pool
Java caches Strings in a pool, only possible because they're immutable.

Common Mistakes

✕ Leaking internal references
Returning this.list directly from a getter lets callers mutate your "immutable" object.
✕ Forgetting constructor copy
Storing a mutable argument directly means the caller can change your data from outside.
✕ Hidden side effects in getters
A method named 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?

Question 3 of 5

What is the main flaw in this "immutable" class?

Question 4 of 5

A pure function in Java:

Question 5 of 5

Given String s = "abc"; and String t = s;, what happens when you call t.toUpperCase()?