IAE Academy

FOR CORE AND IT JOBS · CHAPTER 2 OF 7

Encapsulation and immutability

This chapter shows how a class keeps its own data valid by hiding fields behind methods, and why making an object unchangeable removes a whole family of bugs. You need it to write classes that other code cannot break, and to choose between String and StringBuilder with a reason.

Updated 30 Oct 2026

What you will be able to do

You will hide a class's fields so that only its methods can change them, and prove that a rule such as a balance never going negative holds. You will build an immutable class with defensive copies. You will say what final fixes and what it leaves free. You will pick String or StringBuilder by counting the copying.

Before you start

  1. Chapter 1, Classes and objects in Java

  2. Java arrays, for loops, and throwing and catching an exception

  3. The sum of the first n natural numbers, n(n+1)/2

  4. The sum of powers of 2: 1 + 2 + 4 + ... + 2^(m-1) = 2^m - 1

Hiding fields to keep an invariant

A field that any code can write can hold any value the type allows. A rule about the object, such as a balance that never goes negative, is then only a hope. The fix is to make the field private and let only the class's own methods touch it. Then every change passes through code you wrote, which can refuse a bad change. Java gives four levels of access, set by a modifier before a field or method. A package is a named group of classes, set by the package line at the top of each file; a subclass is a class declared with extends, so it inherits another class's members. Choose the narrowest level that works.

Modifier

Same class

Same package

Subclass in another package

Anywhere

private

yes

no

no

no

(none, called default)

yes

yes

no

no

protected

yes

yes

yes

no

public

yes

yes

yes

yes

Here is the bank account from Chapter 1 with its field hidden. The constructor and both methods refuse any input that would break the rule. Math.addExact adds two longs and throws an ArithmeticException instead of overflowing past the largest long into a negative value. Java 17.

public class Account {
    private long balance;
    public Account(long opening) {
        if (opening < 0) throw new IllegalArgumentException("opening");
        balance = opening;
    }
    public void deposit(long amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount");
        balance = Math.addExact(balance, amount);
    }
    public void withdraw(long amount) {
        if (amount <= 0 || amount > balance) throw new IllegalArgumentException("amount");
        balance -= amount;
    }
    public long getBalance() { return balance; }
}

THE INVARIANT TO PROTECT

Holds at every moment a caller can observe the object, when its methods run one call at a time. b is the value of the private field balance, in rupees.

WHY THE METHODS KEEP IT

Holds when b is private, so no other code writes it, and the constructor starts b at 0 or more. Deposit also needs b + a to fit in a long; Math.addExact throws if it does not. b is the balance before the call, b' after it, a the amount, all in rupees. A call that fails a check throws before b changes.

A getter returns a field's value. It is safe when the value is a primitive or an immutable object. A getter that returns a mutable field, such as an array, hands the caller the object itself; the next section fixes that with a copy. A setter is riskier: a public setBalance(long) would let a caller write any value and undo the argument above. Change a field only in a method that checks the new value against the invariant, and name it for what it does, like withdraw.

WATCH OUT FOR

Private fields with a public setter that checks nothing are not encapsulated. Test: can a caller reach a state your constructor would refuse? If yes, the setter must check or must go.

Immutable classes and final

The strongest way to keep an invariant is to let the object never change after construction. Then it is checked once, in the constructor, and no later code can disturb it. Such an object can also be shared freely between callers, because nobody can change it under another's feet. The recipe has four parts: declare the class final, so no class can extend it to add changeable state or override its methods; make every field private and final, so it is assigned once, in the constructor; offer no setters; and copy any mutable object that enters or leaves. The table and paragraph below say exactly what final does.

final on

What it fixes

What it leaves free

a variable or field

it can be assigned only once

the state of the object it refers to

a method

a subclass cannot override it

who may call it (access modifiers decide that)

a class

no class can extend it

its instances' fields, which can change unless they are final

The first row is the one that surprises people. final fixes the reference, not the object. With final StringBuilder sb = new StringBuilder("a"), the line sb.append("b") is legal and sb now holds ab, but sb = new StringBuilder() does not compile. An array is the same: a final int[] field cannot be pointed elsewhere, yet its cells can change. That is why the recipe needs defensive copies.

DEFENSIVE COPY RULE

Needed for every field of a mutable type, such as an array. On an array, clone() returns a new array of the same length holding the same values; when the elements are primitives or immutable objects, that is a full copy. Without the first copy the caller still holds the stored object; without the second, every caller of the getter does.

WHY SHARING IS THEN SAFE

Holds when the class is final and every field is private, final, and either a primitive, an immutable object or a private copy that no method changes or hands out. s(t) is the object's state, the values of all its fields, at time t after construction.

WORKED EXAMPLE

A caller has int[] a = {2, 3}. It builds an immutable Course from a, then sets a[0] = 99. What does total() give?

Solution
  1. Write the class by the recipe: the class final, every field private and final, and the array copied on the way in and on the way out.

    public final class Course {
        private final String title;
        private final int[] hours;
        public Course(String title, int[] hours) {
            this.title = title;
            this.hours = hours.clone();
        }
        public int[] getHours() { return hours.clone(); }
        public int total() {
            int s = 0;
            for (int h : hours) s += h;
            return s;
        }
    }
  2. The constructor stores hours.clone(), a new array with its own cells. So the caller's array and the field are two separate objects.

  3. Use it from Main.java, beside Course.java:

    public class Main {
        public static void main(String[] args) {
            int[] a = {2, 3};
            Course c = new Course("Java", a);
            a[0] = 99; // changes the caller's array only
            System.out.println(c.total()); // 5
        }
    }
  4. c.total() adds the field's cells, 2 + 3 = 5, because a[0] = 99 wrote only the caller's array. Had the constructor stored the argument itself, the field would be that same array, holding 99 and 3, and total() would return 102.

Answer: 5. The object kept a private copy, so the change to a did not reach it.

String follows this recipe for everything a caller can see. The class is final. It keeps its characters in a private final array that no method changes after construction or hands out; methods that seem to change a string, such as toUpperCase(), return a String and leave the original unchanged. Two non-final fields cache the hash code, which depends only on the characters, so a caller always gets the same value. Immutability is why the hash code can be cached at all, why equal string literals in a program share one object, why a name a method has checked cannot change before it is used, and why Course could store title without a copy.

String against StringBuilder

Because a String never changes, s + "x" cannot extend s. It builds a new String and copies every old character across, then adds one. Do that in a loop and the copying piles up. A StringBuilder is mutable: it keeps an internal array with spare room and writes new characters into the spare room. When the room runs out it allocates a larger array, which we model as doubling, and copies once. We count the character writes for each.

COST OF APPENDING ONE CHARACTER N TIMES TO A STRING

Holds for a loop that does s = s + "x" n times from an empty string. At step k the new string has k characters, all written into a new array. T counts character writes and grows like n²/2.

COST WITH A STRINGBUILDER UNDER DOUBLING

Model: capacity starts at 1 and doubles when an append finds the array full. n ≥ 2 is the number of one-character appends; m is the whole number with 2^(m−1) < n ≤ 2^m. The array fills at sizes 1, 2, ..., 2^(m−1), giving the bracket. The last step uses 2^m < 2n. Java's real growth differs a little; the cost still grows in proportion to n.

WORKED EXAMPLE

A loop appends one character 1000 times. Compare the character writes for String concatenation and for a StringBuilder under the doubling model.

Solution
  1. For String, use the T_String formula, n(n+1)/2, with n = 1000: T = 1000 × 1001 / 2, because each of the 1000 steps rewrites the whole string so far.

  2. That gives 500 500 character writes.

  3. For StringBuilder, find m with . Since and , m = 10.

  4. The array fills at sizes 1, 2, ..., 512, so the copies are . Adding the 1000 appends gives 2023 writes, below the bound 3n = 3000.

  5. The ratio is 500 500 / 2023, about 247.4 to 1. In general, dividing n(n+1)/2 by the bound 3n gives (n + 1)/6, so the ratio is always above (n + 1)/6 and keeps growing with n.

Answer: 500 500 character writes for String against 2023 for StringBuilder.

WATCH OUT FOR

For one or two joins, + is fine and clearer. Test: does the join sit inside a loop whose count is not small? If yes, use StringBuilder and call toString() once at the end.

Check yourself

CHECK YOURSELF 1

A method is declared with no access modifier. Which code can call it?

  1. (A)

    Only code in the same class

  2. (B)

    Code in the same class and the same package

  3. (C)

    Code in the same package and subclasses in other packages

  4. (D)

    Any code

Answer and solution

Answer: (B)

  1. No modifier means default access.

  2. Default access allows the same class and the same package, as the table shows.

  3. Subclasses in other packages need protected, and any code needs public.

CHECK YOURSELF 2One or more options are correct

A class holds a private final int[] field and must be immutable. Which of these are part of a correct design?

  1. (A)

    The constructor stores a clone of the array argument

  2. (B)

    The getter returns the field itself, to save memory

  3. (C)

    The class has no method that writes the array's cells

  4. (D)

    The getter returns a clone of the field

Answer and solution

Answer: (A), (C), (D)

  1. A is the first half of the defensive copy rule.

  2. B hands every caller a reference to the stored array, so they can change its cells.

  3. C is needed because final does not stop cells from changing.

  4. D is the second half of the copy rule.

CHECK YOURSELF 3

A loop runs s = s + "x" 200 times from an empty String. Using the model , how many character writes does it make?

Answer and solution

Answer:

  1. Here n = 200.

  2. T = 200 × 201 / 2 = 40200 / 2 = 20100.

CHECK YOURSELF 4

Given final StringBuilder sb = new StringBuilder("a"); what happens at sb.append("b");?

  1. (A)

    Compile error, because sb is final

  2. (B)

    It compiles, and sb now holds ab

  3. (C)

    It compiles, but sb still holds a

  4. (D)

    A runtime exception is thrown

Answer and solution

Answer: (B)

  1. final fixes the reference sb, which is not reassigned here.

  2. append changes the state of the object sb refers to, which final does not forbid.

  3. So the call is legal and the object now holds ab.