Write a Java Program to Compare time using equals() method


This Java program compares three LocalTime objects and prints out whether each pair of times is the same or not. The program first creates three LocalTime objects using the LocalTime.of() method, passing in hour, minute, and second arguments. It then compares t1 and t2 using the equals() method, and prints out whether they are the same or not. Similarly, it compares t2 and t3 and prints out the result.

If t1 and t2 are not the same, the program will print "Time 1 and Time 2 are Not Same". If they are the same, the program will print "Time 1 and Time 2 are Same". Similarly, if t2 and t3 are not the same, the program will print "Time 2 and Time 3 are Not Same". If they are the same, the program will print "Time 2 and Time 3 are Same".

Note that equals() method is used to compare two LocalTime objects for equality. It compares the hour, minute, second, and nanosecond fields of the two LocalTime objects. If all the fields are equal, the method returns true, otherwise it returns false.

Source Code

import java.util.*;
import java.time.*;
public class Compare_Time
{
	public static void main(String[] args)
	{
		LocalTime t1;
		LocalTime t2;
		LocalTime t3;
 
		t1 = LocalTime.of(12, 10, 23);
		t2 = LocalTime.of(10, 45, 46);
		t3 = LocalTime.of(12, 10, 23);
 
		if (t1.equals(t2) == true)
		{
			System.out.println("Time 1 and Time 2 are Same ");
		}
		else
		{
			System.out.println("Time 1 and Time 2 are Not Same");
		}
 
		if (t2.equals(t3) == true)
		{
			System.out.println("Time 2 and Time 3 are Same");
		}
		else
		{
			System.out.println("Time 2 and Time 3 are Not Same");
		}
	}
}

Output

Time 1 and Time 2 are Not Same
Time 2 and Time 3 are Not Same

Example Programs