Immutability and Modification Methods: plus and minus
What you'll learn: How to modify date/time values using plus and minus methods while preserving immutability.
Temporal Objects Are Immutable
All date-time classes in java.time (like LocalDate, LocalTime, LocalDateTime, and Instant) are immutable. This means once you create them, their internal state never changes. You can't modify a LocalDate in-place like you might update a variable.
Think of it like strings in Java: when you call toUpperCase() on a string, it doesn't change the original string—it returns a new string. Date-time objects work the same way.
Creating Modified Copies
To get a different date or time, you create a new instance using modification methods. The most common families are:
plusmethods: Add time units (plusDays(),plusMonths(),plusHours(),plusWeeks(), etc.)minusmethods: Subtract time units (minusDays(),minusMonths(),minusHours(), etc.)
LocalDate today = LocalDate.of(2024, 1, 15);
LocalDate tomorrow = today.plusDays(1); // Creates new LocalDate: 2024-01-16
LocalDate nextMonth = today.plusMonths(1); // Creates new LocalDate: 2024-02-15
// 'today' is unchanged!
System.out.println(today); // 2024-01-15
System.out.println(tomorrow); // 2024-01-16
LocalTime now = LocalTime.of(14, 30);
LocalTime earlier = now.minusHours(2); // Creates new LocalTime: 12:30
LocalTime later = now.plusMinutes(45); // Creates new LocalTime: 15:15
System.out.println(now); // 14:30 (original unchanged)
Why Immutability Matters
Immutability prevents bugs when passing date-time objects around your code. You never worry about someone accidentally changing a date you're holding onto—it's impossible!
Key Takeaway: Temporal objects in java.time are immutable; plus and minus methods always return new instances with the modification applied, leaving the original unchanged.