A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Java program to compare time using compareTo() method
Q:

Java program to compare time using compareTo() method

0

Java program to compare time using compareTo() method

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program/Source Code:

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

// Java program to compare time using 
// compareTo() 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.compareTo(time2) > 0)
      System.out.println("time1 is later than time2.");
    else if (time1.compareTo(time2) < 0)
      System.out.println("time2 is later than time1.");
    else
      System.out.println("time1 and time2 are same.");

    if (time2.compareTo(time3) > 0)
      System.out.println("time2 is later than time3.");
    else if (time2.compareTo(time3) < 0)
      System.out.println("time3 is later than time2.");
    else
      System.out.println("time2 and time3 are same.");
  }
}

Output:

time2 is later than time1.
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 compareTo() method and printed appropriate messages.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now