Sub topic 2
Immutable Values: Every Change Returns a New Object
Every class in java.time follows one rule. Once you create a date or time object, it never changes. This chapter explains what that rule means, why it protects your programs, and the one mistake that almost every beginner makes because of it.
What "immutable" means
An immutable object is an object whose data cannot change after it is created. A LocalDate holding March 18, 2014 will hold March 18, 2014 for as long as it exists.
A mutable object is the opposite. Its data can change after creation. The old java.util.Date and java.util.Calendar classes are mutable. They have methods such as setTime and add that change the object in place.
How do you "change" a date that cannot change? You ask it for a new date. A method like plusDays(1) does not touch the original. It builds a brand-new object with the new value and returns it to you.
Variables and objects are different things
A variable is a name in your code. A reference is what a variable holds: a pointer to an object somewhere in memory. Several variables can point to the same object.
Immutability is about the object, not the variable. You can still point a variable at a different object. You just cannot alter the object itself.
The most common mistake: ignoring the result
Because plusDays returns a new object, you must keep that object. If you call the method and throw the result away, nothing happens to your date.
import java.time.LocalDate;
public class Immutable {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 1, 31);
date.plusDays(1); // result discarded, date is unchanged
System.out.println(date); // 2024-01-31
LocalDate next = date.plusDays(1);
System.out.println(next); // 2024-02-01
}
}The line date.plusDays(1); compiles and runs without error. It creates February 1, then drops it right away, because no variable holds it. The date variable still points to January 31.
If you want the same variable to hold the new value, assign it back:
import java.time.LocalDate;
public class Reassign {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 1, 31);
date = date.plusDays(1); // variable now points to the new object
System.out.println(date); // 2024-02-01
}
}The original January 31 object did not change here either. The variable date now points to a different object.
Why mutable dates caused bugs
Here is the problem immutability solves. With the old Calendar class, two variables can share one object. A change through one variable shows up through the other.
import java.util.Calendar;
public class SharedCalendar {
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
start.clear();
start.set(2024, Calendar.JANUARY, 31);
Calendar alias = start; // same object, second name
alias.add(Calendar.DAY_OF_MONTH, 1); // changes the shared object
System.out.println(start.get(Calendar.DAY_OF_MONTH)); // 1
System.out.println(start.get(Calendar.MONTH)); // 1 (February, months start at 0)
}
}Nobody touched start directly, yet it moved to February 1. In a large program, that alias might live inside another class or library. You would have no idea who changed your date.
With LocalDate, the same pattern is safe:
import java.time.LocalDate;
public class SharedLocalDate {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024, 1, 31);
LocalDate alias = start;
LocalDate moved = alias.plusDays(1);
System.out.println(start); // 2024-01-31
System.out.println(moved); // 2024-02-01
}
}Benefits you get for free
| Benefit | What it means for you |
|---|---|
| Safe sharing | You can pass a date to any method without fear it comes back changed. |
| No defensive copies | A getter can return its date field directly. Callers cannot alter it. |
| Thread safety | A **thread** is a separate path of execution running at the same time as others. Many threads can read one date with no locks. |
| Safe map keys and set members | A date's value never changes, so its `hashCode` never changes. It stays findable in a `HashMap` or `HashSet`. |
Here is the "no defensive copies" point in code. With java.util.Date, a careful class had to copy the date in its getter. With LocalDate, it does not:
import java.time.LocalDate;
public class Event {
private final LocalDate day;
public Event(LocalDate day) {
this.day = day;
}
public LocalDate getDay() {
return day; // safe: nobody can modify a LocalDate
}
public static void main(String[] args) {
Event launch = new Event(LocalDate.of(2024, 6, 1));
LocalDate d = launch.getDay();
d = d.plusYears(1); // only changes the local variable
System.out.println(launch.getDay()); // 2024-06-01
System.out.println(d); // 2025-06-01
}
}The naming pattern: plus, minus, with
All java.time methods that "modify" a value follow the same naming pattern. Each one returns a new object.
| Prefix | Meaning | Example |
|---|---|---|
| `plus` | Add an amount | `date.plusWeeks(2)` |
| `minus` | Subtract an amount | `date.minusMonths(3)` |
| `with` | Replace one field | `date.withYear(2030)` |
Chaining calls
Since each method returns a new object, you can call the next method straight on the result. This is called method chaining.
import java.time.LocalDate;
public class Chaining {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate result = start.plusMonths(2).minusDays(5).withYear(2025);
System.out.println(start); // 2024-01-15
System.out.println(result); // 2025-03-10
}
}Each step makes a temporary object. plusMonths(2) gives 2024-03-15, minusDays(5) gives 2024-03-10, and withYear(2025) gives 2025-03-10. The start object is untouched.
Edge case: invalid days are adjusted
When a new value would produce a day that does not exist, java.time picks the last valid day of the month instead.
import java.time.LocalDate;
public class Clamping {
public static void main(String[] args) {
LocalDate jan31 = LocalDate.of(2023, 1, 31);
System.out.println(jan31.plusMonths(1)); // 2023-02-28
System.out.println(jan31.withMonth(4)); // 2023-04-30
System.out.println(LocalDate.of(2024, 1, 31).plusMonths(1)); // 2024-02-29
}
}Because of this adjustment, the order of chained calls can change the result. The exercise below shows how.
Edge case: compare with equals, not ==
Two different objects can hold the same date. The == operator checks whether two variables point to the same object. The equals method checks whether two objects hold the same value. Always use equals (or isEqual) for dates.
import java.time.LocalDate;
public class Comparing {
public static void main(String[] args) {
LocalDate a = LocalDate.of(2024, 5, 1);
LocalDate b = LocalDate.of(2024, 4, 30).plusDays(1);
System.out.println(a.equals(b)); // true
System.out.println(a.isEqual(b)); // true
}
}Summary
java.timeobjects never change after creation.plus,minus, andwithmethods return new objects. You must keep the result.- Immutability makes sharing, threading, and map keys safe.
- Chained calls create a new object at each step, and their order can matter.
Exercise
What does this code print, and why? LocalDate d = LocalDate.of(2024, 3, 1); d.minusDays(1); System.out.println(d);
Show answer
It prints 2024-03-01. minusDays(1) returns a new object holding 2024-02-29, but the result is not assigned to any variable, so it is thrown away. The object d points to is immutable and never changed.
Exercise
Starting from LocalDate.of(2024, 1, 30), what do start.plusMonths(1).plusDays(1) and start.plusDays(1).plusMonths(1) each return?
Show answer
The first returns 2024-03-01: plusMonths(1) gives 2024-02-29, then plusDays(1) gives 2024-03-01. The second returns 2024-02-29: plusDays(1) gives 2024-01-31, then plusMonths(1) would give February 31, which does not exist, so it becomes 2024-02-29. The order of chained calls changes the result.
Exercise
A class stores a private final LocalDate field and returns it from a getter. Does the getter need to return a copy to stop callers from changing the stored date?
Show answer
No. LocalDate is immutable, so callers cannot change the object. They can only point their own variable at a new object, which leaves the stored field untouched.