Course contentsShow
← Java
Lesson 1843 of 2,87038. Date and Time API (java.time)Free lesson

Immutability and Modification Methods: plus and minus

Understand that temporal objects are immutable; use plusDays(), minusMonths(), plusHours() to create modified copies.

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:

  • plus methods: Add time units (plusDays(), plusMonths(), plusHours(), plusWeeks(), etc.)
  • minus methods: 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.