Java LocalDate equals( ) Method with Example

In this article we are going to see the use of Java LocalDate class equals( ) method with suitable examples.

Java LocalDate equals( ) Method with Example

This java.time.LocalDate.equals(Object obj) method is used to check a date with another date whether both the dates are equal or not. It returns Boolean value, returns true if equal, false if not equal.

Syntax:

public boolean equals(Object obj)

Where,

  • obj refers to the date which will be passed as parameter to check it is equal with another date or not.

Let’s see the program to understand it more clearly.

Approach:

  • Create two objects of LocalDate class which will hold the parsed dates, here we have taken date1 and date2.
  • Then by using equal() method check both dates are equal or not like date2.equals(date1).
  • Print the final result.

Program:

CASE-1: When both the dates are not equal

import java.time.LocalDate;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it.
     	LocalDate date1 = LocalDate.parse("2022-04-25");
      	System.out.println("date-1: "+date1);
      	//Create an object of LocalDate class and assign a date to it..
      	LocalDate date2 = LocalDate.parse("2022-05-08");
      	System.out.println("date-2: "+date2);
      	//check both the values equal or not and print the final result.
      	System.out.println("Result: "+date2.equals(date1)); 
   	}
}
Output:

date-1: 2022-04-25
date-2: 2022-05-08
Result: false

CASE-2: When both the dates are equal

import java.time.LocalDate;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it.
         LocalDate date1 = LocalDate.parse("2022-05-18");
          System.out.println("date-1: "+date1);
          //Create an object of LocalDate class and assign a date to it..
          LocalDate date2 = LocalDate.parse("2022-05-18");
          System.out.println("date-2: "+date2);
          //check both the values equal or not and print the final result.
          System.out.println("Result: "+date2.equals(date1)); 
       }
}
Output:

date-1: 2022-05-18
date-2: 2022-05-18
Result: true

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.