These are the notes for Java episode 42. Asha books a train for 25 December 2026, and Java's oldest date class prints January 3927. We fix it with the java.time API (LocalDate, LocalDateTime, Duration, ChronoUnit, DateTimeFormatter) and meet its rule: the objects are immutable. Then three more everyday pains and their modern fixes: types written three times (var), strings full of backslashes (text blocks), and chains of instanceof + casts that silently ignore a new payment type (pattern matching and sealed types, where the compiler checks that every case is handled). Every example was run with javac 21.
The problem: the old Date class
Real-life example: booking a train for Christmas. A ticket needs a date (25 December 2026), date maths (days to go, the return trip) and times (leave 22:30, reach 07:45).
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date trip = new Date(2026, 12, 25); // 25 December 2026?
System.out.println("Train on: " + trip);
}
}
Output (the two Note: lines are the compiler's warning):
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Train on: Tue Jan 25 00:00:00 UTC 3927
Two traps in java.util.Date(int year, int month, int day):
| Trap | What it does | Our date |
|---|---|---|
| years are counted from 1900 | 2026 means 1900 + 2026 = 3926 |
year 3926 |
| months are counted from 0 | 12 is the 13th month, which rolls into January of the next year |
January 3927 |
Deprecated means: old, kept only so old code still compiles; don't use it in new code. Date is also mutable (it can be changed after it's made), which makes it unsafe to share between threads.
java.time: LocalDate and friends
Java 8 added the java.time package. LocalDate is a plain date (year, month, day) with no time and no time zone, and months are 1 to 12.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate trip = LocalDate.of(2026, 12, 25);
System.out.println("Train on: " + trip);
System.out.println("Day: " + trip.getDayOfWeek());
System.out.println("Return: " + trip.plusDays(10));
System.out.println("Leap year? " + trip.isLeapYear());
}
}
Output:
Train on: 2026-12-25
Day: FRIDAY
Return: 2027-01-04
Leap year? false
plusDays(10) crossed the year end correctly. Other useful methods: plusWeeks, plusMonths, minusDays, getMonth(), getDayOfMonth(), isBefore(other), isAfter(other), LocalDate.now() (today), LocalDate.parse("2026-12-25").
Immutable: keep the result
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate trip = LocalDate.of(2026, 12, 25);
trip.plusDays(1); // the train is delayed a day
System.out.println("Train on: " + trip);
}
}
Output:
Train on: 2026-12-25
No error, but the delay is lost. Every java.time object is immutable: it can never change, like a String. plusDays returns a new date, and we threw it away. Fix: trip = trip.plusDays(1);. Bonus: immutable objects are safe to share between threads without locks (episode 40).
The family
| Class | Holds | Example |
|---|---|---|
LocalDate |
a date | 2026-12-25 |
LocalTime |
a time of day | 22:30 |
LocalDateTime |
date + time | 2026-12-25T22:30 |
ZonedDateTime |
date + time + time zone | 2026-12-25T22:30+05:30[Asia/Kolkata] |
Instant |
a point on the global timeline (UTC) | 2026-12-25T17:00:00Z |
Duration |
an amount of time in hours/minutes/seconds | PT9H15M |
Period |
an amount in years/months/days | P1Y2M3D |
ChronoUnit |
units for counting: DAYS, HOURS, MONTHS... |
ChronoUnit.DAYS.between(a, b) |
DateTimeFormatter |
how a date/time is printed or parsed | ofPattern("dd-MM-yyyy") |
Days to go, journey time, ticket format
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate booked = LocalDate.of(2026, 11, 7);
LocalDate trip = LocalDate.of(2026, 12, 25);
System.out.println("Days to go: " + ChronoUnit.DAYS.between(booked, trip));
LocalDateTime leave = LocalDateTime.of(2026, 12, 25, 22, 30);
LocalDateTime reach = LocalDateTime.of(2026, 12, 26, 7, 45);
Duration journey = Duration.between(leave, reach);
System.out.println("Journey: " + journey.toHours() + " h "
+ journey.toMinutesPart() + " min");
DateTimeFormatter ticket = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
System.out.println("Ticket: " + leave.format(ticket));
}
}
Output:
Days to go: 48
Journey: 9 h 15 min
Ticket: 25-12-2026 22:30
ChronoUnit.DAYS.between(booked, trip)counts whole days.Duration.between(leave, reach)measures the time between two moments, across midnight.toHours()gives whole hours;toMinutesPart()gives the minutes left over.- Pattern letters:
ddday,MMmonth,yyyyyear,HHhour (0-23),mmminute,EEEEday name,MMMshort month name. Mixing upMMandmmis the classic formatting bug.
var: let the compiler infer the type
The pain: the same type three times
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, List<Integer>> marks = new HashMap<String, List<Integer>>();
marks.put("Asha", List.of(91, 88));
for (Map.Entry<String, List<Integer>> entry : marks.entrySet())
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
Output:
Asha -> [91, 88]
Real-life example: the shopkeeper can see what you hand over. You don't say "keep this parcel, which is a parcel"; he sees it. var (Java 10) lets the compiler read the type from the value on the right: local variable type inference.
import java.util.*;
public class Main {
public static void main(String[] args) {
var marks = new HashMap<String, List<Integer>>();
marks.put("Asha", List.of(91, 88));
for (var entry : marks.entrySet())
System.out.println(entry.getKey() + " -> " + entry.getValue());
var count = 2; // still an int, fixed forever
count = "two";
}
}
Compiler output:
Main.java:10: error: incompatible types: String cannot be converted to int
count = "two";
^
1 error
var count = 2 makes count an int, forever. Java is still statically typed: every variable's type is fixed at compile time. var only saves you typing it.
var needs a value
public class Main {
public static void main(String[] args) {
var bill;
var discount = null;
}
}
Compiler output:
Main.java:3: error: cannot infer type for local variable bill
var bill;
^
(cannot use 'var' on variable without initializer)
Main.java:4: error: cannot infer type for local variable discount
var discount = null;
^
(variable initializer is 'null')
2 errors
The initializer is the value after =. Without one, or with null (which has no useful type), there is nothing to infer from.
var rule |
Example |
|---|---|
local variables inside methods, for loops, try-with-resources |
var list = new ArrayList<String>(); |
| not for fields, method parameters or return types | class A { var x = 1; } does not compile |
must have an initializer that isn't plain null |
var x; / var x = null; do not compile |
var with <> infers Object |
var list = new ArrayList<>(); is an ArrayList<Object>: write the type argument |
| use it when the type is obvious from the right-hand side | var orders = new HashMap<String, List<Integer>>(); |
Text blocks
The pain: quotes inside a string
JSON is a text format apps use to exchange data, full of double quotes.
public class Main {
public static void main(String[] args) {
String order = "{ "item": "masala chai", "qty": 2 }";
System.out.println(order);
}
}
Compiler output:
Main.java:3: error: ';' expected
String order = "{ "item": "masala chai", "qty": 2 }";
^
Main.java:3: error: ';' expected
String order = "{ "item": "masala chai", "qty": 2 }";
^
Main.java:3: error: ';' expected
String order = "{ "item": "masala chai", "qty": 2 }";
^
Main.java:3: error: not a statement
String order = "{ "item": "masala chai", "qty": 2 }";
^
Main.java:3: error: ';' expected
String order = "{ "item": "masala chai", "qty": 2 }";
^
5 errors
The quote before item ends the string, so Java tries to read item as code. The old fix is escape sequences: \" for a quote, \n for a new line:
public class Main {
public static void main(String[] args) {
String order = "{\n \"item\": \"masala chai\",\n \"qty\": 2\n}";
System.out.println(order);
}
}
Output:
{
"item": "masala chai",
"qty": 2
}
It works, but it's unreadable, and one missing backslash breaks it again.
The fix: a text block (Java 15)
public class Main {
public static void main(String[] args) {
String order = """
{
"item": "masala chai",
"qty": 2
}""";
System.out.println(order);
}
}
Output:
{
"item": "masala chai",
"qty": 2
}
- Opens with
"""followed by a new line; the text starts on the next line. - Quotes and new lines need no escapes.
- The indentation that all lines share (incidental whitespace) is removed, so you can indent the block with your code. The closing
"""decides where the text ends; put it on its own line to end with a new line. \at the end of a line joins it with the next;\skeeps a trailing space."...".formatted(a, b)fills%s/%dplaceholders, likeString.format.
Pattern matching
Real-life example: one receipt, many ways to pay. UPI (an ID), card (the last four digits), cash (the note given), and next month a wallet app.
The classic way: instanceof + cast
class Upi { String id = "asha@okbank"; } class Card { String last4 = "4321"; }
class Cash { int given = 50; } class Wallet { String app = "PayQuick"; } // new
public class Main {
static String receipt(Object pay) {
if (pay instanceof Upi) {
Upi u = (Upi) pay; return "UPI from " + u.id;
} else if (pay instanceof Card) {
Card c = (Card) pay; return "Card ending " + c.last4;
} else if (pay instanceof Cash) {
Cash c = (Cash) pay; return "Cash: Rs " + c.given;
}
return "Unknown payment";
}
public static void main(String[] args) {
for (Object p : new Object[]{ new Upi(), new Card(), new Wallet(), "a button" })
System.out.println(receipt(p));
}
}
Output:
UPI from asha@okbank
Card ending 4321
Unknown payment
Unknown payment
A real Wallet payment printed Unknown payment and a String was accepted, with no error anywhere. Each type is also named twice: once in instanceof, once in the cast.
Pattern matching for instanceof (Java 16)
class Upi { String id = "asha@okbank"; }
class Card { String last4 = "4321"; }
public class Main {
static String receipt(Object pay) {
if (pay instanceof Upi u) return "UPI from " + u.id;
if (pay instanceof Card c) return "Card ending " + c.last4;
return "Unknown payment";
}
public static void main(String[] args) {
System.out.println(receipt(new Upi()));
System.out.println(receipt(new Card()));
}
}
Output:
UPI from asha@okbank
Card ending 4321
pay instanceof Upi u tests the type and, if it matches, creates u already cast to Upi. The variable u is called a pattern variable; it exists only where the test is known to be true.
Sealed classes and pattern matching for switch
Real-life example: the printed list of payment methods.
| At the stall | In Java | Meaning |
|---|---|---|
| "We accept: UPI, card, cash", a fixed list | sealed interface Payment permits Upi, Card, Cash |
only the listed types may implement it |
| the cashier's checklist, one line per method | switch (pay) { case Upi u -> ... } |
one case per type |
| the manager spots a missing line | compile error | a missing case is caught by the compiler |
A sealed class or interface (Java 17) lists, with permits, exactly which classes may extend or implement it. Each permitted class must be final, sealed or non-sealed; records (episode 24) are automatically final.
Forget a case: the compiler refuses
sealed interface Payment permits Upi, Card, Cash {}
record Upi(String id) implements Payment {}
record Card(String last4) implements Payment {}
record Cash(int given) implements Payment {}
public class Main {
static String receipt(Payment pay) {
return switch (pay) {
case Upi u -> "UPI from " + u.id();
case Card c -> "Card ending " + c.last4();
};
}
public static void main(String[] args) {
System.out.println(receipt(new Upi("asha@okbank")));
System.out.println(receipt(new Cash(50)));
}
}
Compiler output:
Main.java:8: error: the switch expression does not cover all possible input values
return switch (pay) {
^
1 error
A switch expression (it produces a value) must be exhaustive: cover every possible input. Because Payment is sealed, the compiler knows the full list and sees Cash is missing.
Every case, plus a guard
sealed interface Payment permits Upi, Card, Cash {}
record Upi(String id) implements Payment {}
record Card(String last4) implements Payment {}
record Cash(int given) implements Payment {}
public class Main {
static String receipt(Payment pay) {
return switch (pay) {
case Upi u -> "UPI from " + u.id();
case Card c -> "Card ending " + c.last4();
case Cash c when c.given() >= 500 -> "Cash: Rs " + c.given() + " (check the note!)";
case Cash c -> "Cash: Rs " + c.given();
};
}
public static void main(String[] args) {
for (Payment p : new Payment[]{ new Upi("asha@okbank"), new Card("4321"), new Cash(50), new Cash(500) })
System.out.println(receipt(p));
}
}
Output:
UPI from asha@okbank
Card ending 4321
Cash: Rs 50
Cash: Rs 500 (check the note!)
case Cash c when c.given() >= 500is a guarded pattern: it matches only when the condition is true. Put it before the plaincase Cash c, or the compiler reports that it is dominated (can never match).- No
defaultis needed: the sealed list is complete. Leavingdefaultout is better, because then a new type causes a compile error instead of silently hittingdefault. - Java 21 also has record patterns:
case Upi(String id) -> "UPI from " + idtakes the record apart directly.
A new type that isn't permitted
sealed interface Payment permits Upi, Card, Cash {}
record Upi(String id) implements Payment {}
record Card(String last4) implements Payment {}
record Cash(int given) implements Payment {}
record Wallet(String app) implements Payment {}
public class Main {
public static void main(String[] args) {
System.out.println(new Wallet("PayQuick"));
}
}
Compiler output:
Main.java:5: error: class is not allowed to extend sealed class: Payment (as it is not listed in its 'permits' clause)
record Wallet(String app) implements Payment {}
^
1 error
To add a wallet you must add it to permits, and then every switch over Payment without a Wallet case stops compiling until you handle it. The silent "Unknown payment" bug can't happen any more.
Common mistakes (and what you see)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
new Date(2026, 12, 25) |
Tue Jan 25 00:00:00 UTC 3927, and Note: Main.java uses or overrides a deprecated API. |
years from 1900, months from 0 | LocalDate.of(2026, 12, 25) |
trip.plusDays(1); |
no error: the date doesn't change | java.time objects are immutable |
trip = trip.plusDays(1); |
ofPattern("dd-mm-yyyy") |
no error: minutes printed where the month should be | mm = minutes, MM = month |
"dd-MM-yyyy" |
var bill; |
error: cannot infer type for local variable bill / (cannot use 'var' on variable without initializer) |
nothing to infer from | var bill = 0; |
var discount = null; |
error: cannot infer type for local variable discount / (variable initializer is 'null') |
null has no useful type |
give a real type: Integer discount = null; |
var count = 2; count = "two"; |
error: incompatible types: String cannot be converted to int |
var is still static typing |
keep one type per variable |
"{ "item": "chai" }" |
error: ';' expected (several times), error: not a statement |
a quote ends the string | a text block, or \" |
| switch over a sealed type missing a case | error: the switch expression does not cover all possible input values |
not exhaustive | add the missing case |
| implementing a sealed interface without being listed | error: class is not allowed to extend sealed class: Payment (as it is not listed in its 'permits' clause) |
the list is closed | add it to permits |
Mini project: a train ticket printer
Everything from today together: a sealed Coach type with records, a switch with a guard for the fare, LocalDateTime + Duration for the times, var, and a text block for the ticket.
import java.time.*;
import java.time.format.DateTimeFormatter;
sealed interface Coach permits Sleeper, AC3, AC2 {}
record Sleeper(int berth) implements Coach {}
record AC3(int berth) implements Coach {}
record AC2(int berth, boolean window) implements Coach {}
public class Main {
static int fare(Coach c) {
return switch (c) {
case Sleeper s -> 450;
case AC3 a -> 1200;
case AC2 a when a.window() -> 1850;
case AC2 a -> 1750;
};
}
public static void main(String[] args) {
var leave = LocalDateTime.of(2026, 12, 25, 22, 30);
var journey = Duration.ofHours(9).plusMinutes(15);
var reach = leave.plus(journey);
var fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
Coach seat = new AC2(14, true);
var ticket = """
Passenger : %s
Coach : %s
Departs : %s
Arrives : %s
Fare : Rs %d
""".formatted("Asha", seat, leave.format(fmt), reach.format(fmt), fare(seat));
System.out.print(ticket);
}
}
Output:
Passenger : Asha
Coach : AC2[berth=14, window=true]
Departs : 25-12-2026 22:30
Arrives : 26-12-2026 07:45
Fare : Rs 1850
leave.plus(journey) adds a Duration to a date-time; the arrival correctly rolls over to the next day. A record's toString() prints AC2[berth=14, window=true] automatically.
Practice
- Your age in days with
ChronoUnit. - Format today as
Saturday, 07 Nov 2026. - Print a bill as a text block with
String.formatted. - A sealed
Shape(Circle,Square) with an area switch.
Solution 1
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate born = LocalDate.of(2005, 8, 15);
LocalDate today = LocalDate.of(2026, 11, 7); // or LocalDate.now()
System.out.println("Days alive: " + ChronoUnit.DAYS.between(born, today));
System.out.println("Age: " + born.until(today).getYears() + " years");
}
}
Output:
Days alive: 7754
Age: 21 years
born.until(today) returns a Period; getYears() is the age in whole years.
Solution 2
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 11, 7); // or LocalDate.now()
var f = DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy", Locale.ENGLISH);
System.out.println(today.format(f));
}
}
Output:
Saturday, 07 Nov 2026
EEEE is the full day name, MMM the short month name. Locale.ENGLISH makes the names English on any machine.
Solution 3
public class Main {
public static void main(String[] args) {
var bill = """
SyntaxPilot Chai Stall
----------------------
%-12s Rs %4d
%-12s Rs %4d
----------------------
Total Rs %4d
""".formatted("Masala chai", 30, "Samosa", 40, 70);
System.out.print(bill);
}
}
Output:
SyntaxPilot Chai Stall
----------------------
Masala chai Rs 30
Samosa Rs 40
----------------------
Total Rs 70
%-12s pads a string to 12 characters, left-aligned; %4d right-aligns a number in 4 characters. The closing """ on its own line ends the text with a new line, so print is enough.
Solution 4
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
public class Main {
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.side() * q.side();
};
}
public static void main(String[] args) {
System.out.printf("Circle r=2: %.2f%n", area(new Circle(2)));
System.out.printf("Square 3: %.2f%n", area(new Square(3)));
}
}
Output:
Circle r=2: 12.57
Square 3: 9.00
Quick quiz
LocalDate d = LocalDate.of(2026, 1, 31);
d.plusMonths(1);
d = d.plusDays(1);
System.out.println(d);
A. 2026-03-01 B. 2026-02-01 C. 2026-02-28 D. 2026-03-03
Answer
B. 2026-02-01. plusMonths(1) returns a new date that is thrown away, so d is still 2026-01-31; plusDays(1) is kept. (Had we kept it, plusMonths(1) on 31 January gives 2026-02-28: java.time clamps to the last valid day.)
Interview questions
- What was wrong with
java.util.DateandCalendar? Mutable (not thread-safe), confusing (years from 1900, months from 0), a date class that also holds time, poor formatting (SimpleDateFormatisn't thread-safe). LocalDateTimevsZonedDateTimevsInstant? Local = no zone (a wall-clock time); Zoned = with a time zone and its rules; Instant = a point on the UTC timeline, good for timestamps.DurationvsPeriod? Duration is time-based (hours, minutes, seconds); Period is date-based (years, months, days).- Why are java.time classes immutable, and what does it mean for you? Safe to share and cache; every "change" returns a new object, so you must keep the return value.
- Is
vardynamic typing? No. The type is inferred once at compile time and fixed; Java stays statically typed. - Where can't you use
var? Fields, method parameters, return types, without an initializer, or with a plainnullinitializer. - What are text blocks and how is indentation handled?
"""multi-line strings (Java 15); common leading whitespace is stripped, the closing delimiter's position matters. - What is a sealed class? A class or interface that lists its allowed subtypes with
permits(Java 17), so the hierarchy is closed and known to the compiler. - What is exhaustiveness in a switch? A switch expression must handle every possible value; with sealed types and enums the compiler can check this without
default. - What is a guarded pattern?
case Type t when condition; it matches only if the condition is true. - Pattern matching for instanceof vs the old style?
if (o instanceof Upi u)tests and casts in one step, removing a separate cast that could be wrong.
Glossary
| Term | Meaning |
|---|---|
java.util.Date |
Java's original date-time class; mutable and confusing; avoid it in new code |
| Deprecated | old, kept for compatibility, not to be used in new code |
| Mutable / immutable | can / cannot be changed after it's made |
java.time |
the modern date and time API (Java 8) |
LocalDate |
a date without time or time zone |
LocalTime |
a time of day |
LocalDateTime |
a date and a time, without a time zone |
ZonedDateTime |
a date-time with a time zone |
Instant |
a point on the UTC timeline |
Duration |
an amount of time in hours, minutes, seconds |
Period |
an amount of time in years, months, days |
ChronoUnit |
an enum of time units used for counting, e.g. DAYS.between |
DateTimeFormatter |
turns dates into text and back, using a pattern like dd-MM-yyyy |
| Leap year | a year with 29 February |
var |
a local variable whose type the compiler infers from its initializer |
| Type inference | the compiler working out a type from the code |
| Initializer | the value after = in a declaration |
| Statically typed | every variable's type is fixed at compile time |
| JSON | a text format for data, with quoted names and values |
| Escape sequence | a backslash code inside a string, such as \" or \n |
| Text block | a multi-line string literal in """ |
| Incidental whitespace | indentation shared by all lines of a text block; removed automatically |
formatted |
fills %s, %d placeholders in a string |
instanceof |
tests whether an object is of a type |
| Cast | treating a value as a more specific type: (Upi) pay |
| Pattern matching | testing a value's shape and extracting parts in one step |
| Pattern variable | the variable a pattern creates, e.g. u in instanceof Upi u |
| Sealed class / interface | a type that lists its allowed subtypes with permits |
permits |
the list of classes allowed to extend a sealed type |
non-sealed |
a permitted subclass that re-opens the hierarchy |
| Switch expression | a switch that produces a value, with case ... -> |
| Exhaustive | covering every possible input |
| Guarded pattern | a case with when condition |
| Dominated case | a case that can never match because an earlier case covers it |
| Record pattern | (Java 21) a pattern that takes a record apart: case Upi(String id) |
Summary
- Don't use
java.util.Date: years from 1900, months from 0, mutable. Usejava.time:LocalDate,LocalDateTime, months 1 to 12. - java.time objects are immutable: keep what
plusDaysreturns.Duration,ChronoUnitandDateTimeFormatterdo the maths and formatting (MMmonth,mmminutes). varinfers a local variable's type from its initializer; the type is still fixed. Novarwithout a value, withnull, or for fields and parameters.- Text blocks (
""") hold multi-line text with no escapes. - Pattern matching (
instanceof Upi u,case Cash c when ...) tests and extracts in one step. With a sealed type, the compiler checks that a switch handles every permitted type. - Next episode: inside the JVM: class loading, memory areas and garbage collection.