12.4 java.time Calendar API & Simple Predicate Lambdas

Key Takeaways

  • The date, time, period, and formatter classes here are immutable. Use static factories such as LocalDate.of(...), Period.ofDays(...), and DateTimeFormatter.ofPattern(...), or an appropriate formatter constant.

  • Calling Period.of(0, 1, 0).ofDays(5) returns only P5D because ofDays is a static method, and adding a Period of days to LocalTime throws UnsupportedTemporalTypeException

  • Invalid calendar values such as LocalDate.of(2026, 2, 29) throw DateTimeException at runtime, and discarding return values of plusDays/minusMonths leaves the original date unchanged

  • DateTimeFormatter patterns distinguish MM (month) from mm (minute) and HH (24-hour) from hh (12-hour); formatting a LocalDate with time fields throws UnsupportedTemporalTypeException

  • A Predicate<T> supplies boolean test(T t). A lambda can omit parentheses around one untyped parameter and can capture definitely assigned local variables that are final or effectively final.

Last updated: November 2026

Part A: The java.time Calendar and Formatting API

Java SE 8 added immutable, thread-safe date and time types in java.time and java.time.format. Use factories such as LocalDate.now(), LocalDate.of(...), and LocalDate.parse(...) for dates, or DateTimeFormatter.ofPattern(...) for a custom formatter.

ClassWhat It RepresentsDefault toString() FormatCommon of(...) Factories
LocalDateDate only (year, month, day)2026-11-27LocalDate.of(2026, 11, 27) or LocalDate.of(2026, Month.NOVEMBER, 27)
LocalTimeTime only (hour, min, sec, nano)14:30 or 14:30:05LocalTime.of(14, 30), (14, 30, 5), (14, 30, 5, 100)
LocalDateTimeDate + time (no time zone)2026-11-27T14:30LocalDateTime.of(date, time) or of(2026, 11, 27, 14, 30)
PeriodDate-based span (years, months, days)P1Y2M5DPeriod.of(1, 2, 5), ofYears(1), ofMonths(2), ofWeeks(3), ofDays(5)

Notice two huge improvements over legacy Java dates: LocalDate months are 1-based (1 = January, 11 = November), and invalid calendar inputs immediately throw DateTimeException at runtime instead of silently rolling over:

LocalDate leap = LocalDate.of(2024, Month.FEBRUARY, 29); // Valid (2024 is leap year)
// LocalDate bad = LocalDate.of(2026, 2, 29);          // Throws DateTimeException
// LocalTime badTime = LocalTime.of(24, 0);            // Throws DateTimeException

Immutability and Chaining Manipulation Methods

Just like String, LocalDate, LocalTime, and LocalDateTime are immutable. These methods return the adjusted value without changing the original. Save their result when later code needs the adjustment:

LocalDate date = LocalDate.of(2026, 1, 31);
date.plusMonths(1);                   // Discarded! date is still 2026-01-31
LocalDate next = date.plusMonths(1);  // Clamped to 2026-02-28
LocalDateTime dt = LocalDateTime.of(next, LocalTime.of(10, 15))
                                .minusDays(2)
                                .plusHours(3);
System.out.println(dt);               // Prints: 2026-02-26T13:15

Two Classic Period Traps

  1. Static Chaining Trap: Because ofYears, ofMonths, ofWeeks, and ofDays on Period are static methods, chaining them discards earlier calls and returns only the last Period:
Period wrong = Period.ofYears(1).ofMonths(2).ofDays(5); // P5D (ONLY 5 days!)
Period right = Period.of(1, 2, 5);                      // P1Y2M5D
  1. UnsupportedTemporalTypeException Trap: Period represents days/months/years, which LocalTime does not possess:
LocalTime t = LocalTime.of(9, 0);
// t.plus(Period.ofDays(1));          // Throws UnsupportedTemporalTypeException
LocalDate d = LocalDate.of(2026, 5, 1);
System.out.println(d.plus(Period.ofWeeks(2))); // 2026-05-15

DateTimeFormatter Constants, Styles, and Patterns

java.time.format.DateTimeFormatter formats and parses temporal objects without mutability bugs:

  • ISO constants: DateTimeFormatter.ISO_LOCAL_DATE, ISO_LOCAL_TIME, ISO_LOCAL_DATE_TIME.
  • Localized styles: DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT) (MEDIUM, LONG, FULL), ofLocalizedTime(...), ofLocalizedDateTime(...).
  • Custom patterns (ofPattern):
    • yyyy = year-of-era padded to at least four digits for ordinary positive years, MM = 2-digit month (01–12), dd = day of month
    • HH = 24-hour (00–23), hh = 12-hour (01–12), mm = minute, ss = second
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime meeting = LocalDateTime.of(2026, 11, 27, 14, 5);
System.out.println(meeting.format(fmt)); // 27/11/2026 14:05
System.out.println(fmt.format(meeting)); // 27/11/2026 14:05 (symmetric!)

LocalDate parsed = LocalDate.parse("2026-11-27"); // Uses ISO_LOCAL_DATE
// LocalDate.of(2026, 11, 27).format(fmt); // Throws UnsupportedTemporalTypeException (no HH:mm)

Caution

Formatting a LocalDate with a formatter containing time fields (like HH:mm or ofLocalizedTime), or formatting a LocalTime with date fields (like yyyy or ofLocalizedDate), compiles cleanly and throws UnsupportedTemporalTypeException at runtime. Parsing malformed text throws DateTimeParseException.


Part B — Predicate<T> and Simple Lambda Expressions

In Java SE 8, java.util.function.Predicate<T> is a functional interface with one abstract method, shown here without the interface’s default and static methods:

public interface Predicate<T> {
    boolean test(T t);
}

A lambda expression provides an inline implementation of a functional interface without writing an anonymous inner class. Common exam uses include ArrayList.removeIf(Predicate) and custom filter methods:

import java.util.*;
import java.util.function.Predicate;

List<String> words = new ArrayList<>(Arrays.asList("ant", "apple", "bat"));
words.removeIf(s -> s.startsWith("a"));
System.out.println(words); // [bat]

Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(8)); // true

Exact Lambda Syntax Rules

A lambda has the form (parameters) -> body. Memorize every legal and illegal variation:

FeatureValid SyntaxInvalid Syntax (Compiler Error)
Single untyped params -> s.isEmpty() or (s) -> s.isEmpty()—
Single typed param(String s) -> s.isEmpty()String s -> s.isEmpty() (missing ())
Zero or 2+ params() -> true, (a, b) -> a.equals(b)a, b -> a.equals(b) (missing ())
Mixed param types(int a, int b) -> a > b(int a, b) -> a > b (cannot mix typed & untyped)
Expression bodys -> s.length() > 2s -> return s.length() > 2; (return forbidden without {})
Block body ({ ... })s -> { return s.length() > 2; }s -> { s.length() > 2 } (missing return and ;)
Variable shadowings -> s.length() > 0 (fresh name)int s = 1; Predicate<String> p = s -> s.isEmpty(); (redeclares s)

Effectively Final Variable Capture

A lambda can read local variables from its enclosing method only if those variables are definitely assigned before the lambda and either declared final or effectively final. An initialized local stays effectively final if it never appears on the left of an assignment or as the operand of an increment or decrement. A local declared without an initializer can be assigned on mutually exclusive branches and still be effectively final:

int minLen = 3;                 // Effectively final if never modified
Predicate<String> ok = s -> s.length() >= minLen;

int limit = 3;
Predicate<String> bad = s -> s.length() >= limit; // DOES NOT COMPILE
limit = 4;                      // Reassignment breaks effective finality!

The effective-finality rule applies to captured locals, parameters, and exception parameters. Fields follow normal access, static-context, and final rules. A lambda can use an enclosing instance field when it has access to the enclosing instance.

Loading diagram...
Choosing and Constructing Immutable java.time Types
Test Your Knowledge

What is printed by the following Java SE 8 code?

LocalDate date = LocalDate.of(2026, 3, 10);
date.plusDays(3);
Period p = Period.ofMonths(1).ofDays(5);
date = date.plus(p);
System.out.println(date);
A

2026-04-18

B

2026-04-15

C

2026-03-18

D

2026-03-15

Test Your Knowledge

Which statement accurately describes the outcome of running the following snippet?

LocalDate d = LocalDate.of(2026, 11, 27);
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(d.format(f));
A

Prints 2026-11-27 00:00

B

Throws UnsupportedTemporalTypeException at runtime

C

Throws DateTimeParseException at runtime

D

Compilation fails because LocalDate has no format method

Test Your Knowledge

Which of the following lines compiles cleanly as a valid Java SE 8 lambda implementing Predicate<String>, assuming Predicate is imported?

A

Predicate<String> p1 = String s -> s.isEmpty();

B

Predicate<String> p2 = s -> { s.isEmpty(); };

C

Predicate<String> p3 = (String s) -> { return s.length() > 2; };

D

Predicate<String> p4 = (s) -> return s.startsWith("J");

Sections you finish are checked off in the contents.

Congratulations!

You've completed this section

Continue exploring other exams