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(...), andDateTimeFormatter.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>suppliesboolean 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.
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.
| Class | What It Represents | Default toString() Format | Common of(...) Factories |
|---|---|---|---|
LocalDate | Date only (year, month, day) | 2026-11-27 | LocalDate.of(2026, 11, 27) or LocalDate.of(2026, Month.NOVEMBER, 27) |
LocalTime | Time only (hour, min, sec, nano) | 14:30 or 14:30:05 | LocalTime.of(14, 30), (14, 30, 5), (14, 30, 5, 100) |
LocalDateTime | Date + time (no time zone) | 2026-11-27T14:30 | LocalDateTime.of(date, time) or of(2026, 11, 27, 14, 30) |
Period | Date-based span (years, months, days) | P1Y2M5D | Period.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
- Static Chaining Trap: Because
ofYears,ofMonths,ofWeeks, andofDaysonPeriodarestaticmethods, chaining them discards earlier calls and returns only the lastPeriod:
Period wrong = Period.ofYears(1).ofMonths(2).ofDays(5); // P5D (ONLY 5 days!)
Period right = Period.of(1, 2, 5); // P1Y2M5D
UnsupportedTemporalTypeExceptionTrap:Periodrepresents days/months/years, whichLocalTimedoes 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 monthHH= 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:
| Feature | Valid Syntax | Invalid Syntax (Compiler Error) |
|---|---|---|
| Single untyped param | s -> 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 body | s -> s.length() > 2 | s -> return s.length() > 2; (return forbidden without {}) |
Block body ({ ... }) | s -> { return s.length() > 2; } | s -> { s.length() > 2 } (missing return and ;) |
| Variable shadowing | s -> 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.
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);
2026-04-18
2026-04-15
2026-03-18
2026-03-15
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));
Prints 2026-11-27 00:00
Throws UnsupportedTemporalTypeException at runtime
Throws DateTimeParseException at runtime
Compilation fails because LocalDate has no format method
Which of the following lines compiles cleanly as a valid Java SE 8 lambda implementing Predicate<String>, assuming Predicate is imported?
Predicate<String> p1 = String s -> s.isEmpty();
Predicate<String> p2 = s -> { s.isEmpty(); };
Predicate<String> p3 = (String s) -> { return s.length() > 2; };
Predicate<String> p4 = (s) -> return s.startsWith("J");
Sections you finish are checked off in the contents.
You've completed this section
Continue exploring other exams