Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

`LocalDate.equals(Object)` — date equality

Use `LocalDate.equals` to check whether two `LocalDate` values represent the same ISO date. Use `isEqual` to compare the underlying day across calendars.

Version: Java SE 21

Syntax

public boolean equals(Object obj)
// Instance method of java.time.LocalDate
boolean sameDate = date.equals(other);

In Java SE 21, the LocalDate.equals(Object obj) instance method returns true only if obj is a java.time.LocalDate with the same year, month, and day of month. LocalDate represents an ISO-8601 date without a time of day or time zone, not an instant.

date.equals(null) returns false when date is non-null. If date itself is null, calling date.equals(other) throws NullPointerException. If either reference may be null, use Objects.equals(date, other): two nulls return true, and exactly one returns false.

The == operator compares references, not date values. Equal LocalDate values have the same hashCode(), but matching hash codes do not prove equality.

equals returns false for another type, even if a JapaneseDate denotes the same day. Use isEqual(ChronoLocalDate) to compare the epoch-day number without regard to calendar system; the argument must not be null. Use compareTo(ChronoLocalDate) for ordering: it uses the calendar system to break ties when the day is the same.

Examples

import java.time.LocalDate;
import java.time.chrono.JapaneseDate;
import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2024, 2, 29);
        LocalDate sameDate = LocalDate.parse("2024-02-29");
        LocalDate nextDate = date.plusDays(1);
        JapaneseDate japaneseDate = JapaneseDate.from(date);
        LocalDate missing = null;

        System.out.println("Same ISO date: " + date.equals(sameDate));
        System.out.println("Next ISO date: " + date.equals(nextDate));
        System.out.println("Null argument: " + date.equals(null));
        System.out.println("Different calendar, equals: " + date.equals(japaneseDate));
        System.out.println("Different calendar, isEqual: " + date.isEqual(japaneseDate));
        System.out.println("Two missing dates: " + Objects.equals(missing, missing));
    }
}

Result

Same ISO date: true
Next ISO date: false
Null argument: false
Different calendar, equals: false
Different calendar, isEqual: true
Two missing dates: true

`date` and `sameDate` are created in different ways but have the same value. `japaneseDate` denotes the same day in another calendar, so `equals` returns `false` while `isEqual` returns `true`.

Related lessons

  • Java · Lesson 4 · Advanced · Version: 2

Sources