Java final and Immutable Objects: Assign Once, Share Safely
A whiteboard can be wiped; a receipt can't. final fixes a variable, a parameter, a method or a class, but a final array's cells still change. An immutable Money class returns a new object from plus(15), so 120 USD stays 120 USD for everyone sharing it.
What you will learn
- Use final on variables, constants and parameters
- Explain why a final array's cells can still change
- Build an immutable class with a final class, private final fields and no setters
- Explain why an immutable object is safe to share between variables
Before you start
- Java access modifiers and encapsulation
- Java arrays
Think of a whiteboard in a shop showing "Total: 120 USD". The total changes, so you wipe it and write 135: the 120 is gone. Now think of a printed receipt. It also says 120 USD, but it can't be changed. If the total changes, the shop prints a new receipt and the old one stays as it was. An immutable object works like the receipt: to get a different value, you create a new object.
A final variable
package org.studyeasy.s03l07;
public class Ex01_FinalVariable {
static final int MAX_ITEMS = 5; // a constant for the program
public static void main(String[] args) {
final String orderId = "ORD-7781"; // assigned once, here
System.out.println("Order " + orderId);
System.out.println("Max items: " + MAX_ITEMS);
}
}
Order ORD-7781
Max items: 5
static final makes a constant (named in capitals by convention). A final local is assigned once and never again: orderId = "ORD-9999"; is a compile error.
A final parameter
package org.studyeasy.s03l07;
public class Ex02_FinalParameter {
// final: the method can read bill but cannot change it
static int withTip(final int bill) {
return bill + bill / 10; // 10% tip
}
public static void main(String[] args) {
System.out.println("Bill 80: " + withTip(80));
System.out.println("Bill 150: " + withTip(150));
}
}
Bill 80: 88
Bill 150: 165
Reading bill is fine. Add bill = bill + 5; inside the method and the compiler says "final parameter bill may not be assigned". It's a small safety check: the method returns a new value instead of changing the one it received.
final is not frozen
package org.studyeasy.s03l07;
public class Ex03_FinalArray {
public static void main(String[] args) {
final int[] scores = {72, 85, 90};
scores[0] = 100; // allowed: same array, new content
System.out.println("First score: " + scores[0]);
}
}
First score: 100
scores keeps this array for good, so scores = new int[3]; fails with "cannot assign a value to final variable scores". Changing a cell is still allowed. The same is true for any object: final fixes the reference, not the object's contents.
An immutable Money class
package org.studyeasy.s03l07;
public final class Money {
private final int amount; // set once, in the constructor
private final String currency;
public Money(int amount, String currency) {
this.amount = amount;
this.currency = currency;
}
// No setters. Adding returns a NEW Money
public Money plus(int extra) {
return new Money(amount + extra, currency);
}
public String toString() {
return amount + " " + currency;
}
// final method: no child class can replace it
public final String label() {
return "Money in " + currency;
}
}
public final class Money: a final class can't have child classes. Writeclass TipMoney extends Moneyand Java says "cannot inherit from final Money".private finalfields are set once, in the constructor, and there are no setters.plusdoesn't change this object. It returns a newMoney.label()is a final method: a child class couldn't replace it (relevant once you meet overriding).
Safe to share
package org.studyeasy.s03l07;
public class Ex04_SafeToShare {
public static void main(String[] args) {
Money price = new Money(120, "USD");
Money shared = price; // two variables, one object
Money withTip = price.plus(15); // a new object
System.out.println("price = " + price);
System.out.println("shared = " + shared);
System.out.println("withTip = " + withTip);
}
}
price = 120 USD
shared = 120 USD
withTip = 135 USD
price and shared are two names for one object, which is normally risky: change it through one and the other sees it (as in classes and objects). Here nobody can change it. price.plus(15) builds a brand new Money with 135, and everyone holding the first one still sees 120 USD. price.setAmount(200) doesn't even compile: there's no setter.
Recap: five places for final
| Where | Effect |
|---|---|
| Variable | assigned once, never again |
| Parameter | read it, never reassign it |
| Array (or any reference) | always the same object; its contents can change |
| Method | a child class can't replace it |
| Class | can't have child classes |
Private final fields, no setters, and methods that return a new object: that's an immutable class, and its objects are safe to share anywhere. Java's own String works this way, as you'll see in strings as objects.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
