Builder: toBuilder() copies an instance into a new builder

toBuilder() reads the immutable object's own fields back into a fresh Builder, so an existing value can be tweaked without hand-copying every field. The original object is untouched; only the new build() call produces a changed copy.

Code
class Profile {
    final String name;
    final int age;
    private Profile(String name, int age) { this.name = name; this.age = age; }
    Builder toBuilder() { return new Builder().name(name).age(age); }
    public String toString() { return name + "(" + age + ")"; }
    static class Builder {
        private String name;
        private int age;
        Builder name(String n) { name = n; return this; }
        Builder age(int a) { age = a; return this; }
        Profile build() { return new Profile(name, age); }
    }
}
Profile original = new Profile.Builder().name("Sam").age(30).build();
Profile updated = original.toBuilder().age(31).build();
System.out.println("Original: " + original);
System.out.println("Updated: " + updated);
Output
Original: Sam(30)
Updated: Sam(31)
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms