Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

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
The final variable scores points to an array 72, 85, 90. scores[0] = 100 changes the first cell to 100: allowed. scores = new int[3] would point to a different array: refused by the compiler. final scores 72 → 1008590 new int[3] cells can change refused final fixes which array the variable points to, not what's inside it.
A final reference can't be re-pointed, but the object it points to can still change.

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. Write class TipMoney extends Money and Java says "cannot inherit from final Money".
  • private final fields are set once, in the constructor, and there are no setters.
  • plus doesn't change this object. It returns a new Money.
  • 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

WhereEffect
Variableassigned once, never again
Parameterread it, never reassign it
Array (or any reference)always the same object; its contents can change
Methoda child class can't replace it
Classcan'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.

Keep going in Java · 29 of 79

Previous
Java Access Modifiers and Encapsulation: Private Data, Public Methods
Next post
Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A final variable
  • A final parameter
  • final is not frozen
  • An immutable Money class
  • Safe to share
  • Recap: five places for final
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.