Java program to compare time using equals() method

Java example to demonstrate how to compare time using equals() method?
Submitted by Nidhi, on April 03, 2022

Problem Solution:

In this program, we will create objects of the LocalTime class with the specified time. Then we will compare two times using the equals() method and print appropriate messages.

Program/Source Code:

The source code to compare time using the equals() method is given below. The given program is compiled and executed successfully.

// Java program to compare time using 
// equals() method

import java.util.*;
import java.time.*;

public class Main {
  public static void main(String[] args) {
    LocalTime time1;
    LocalTime time2;
    LocalTime time3;

    time1 = LocalTime.of(10, 15, 18); //10:15:18
    time2 = LocalTime.of(11, 45, 46); //11:45:46
    time3 = LocalTime.of(11, 45, 46); //11:45:46

    if (time1.equals(time2) == true)
      System.out.println("time1 and time2 are same.");
    else
      System.out.println("time1 and time2 are not same.");

    if (time2.equals(time3) == true)
      System.out.println("time2 and time3 are same.");
    else
      System.out.println("time2 and time3 are not same.");
  }
}

Output:

time1 and time2 are not same.
time2 and time3 are same.

Explanation:

In the above program, we imported the "java.util.*" package to use the Date class. Here, we created a class Main that contains a static method main(). The main() method is the entry point for the program, here we created three objects of the LocalTime class with the specified time. Then we compared created objects using the equals() method and printed appropriate messages.

Java Date and Time Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.