Write a program to show the digital clock on the console.
Objective
Write a Java program to simulate a digital clock on the console using Thread.sleep().
Algorithm / Approach
- Start an infinite
while(true)loop. - Inside the loop, get the current time using
new Date()and extract hours, minutes, and seconds. - Print the time using
System.out.printfwith the carriage return character\rto overwrite the same line. - Pause the current thread for exactly 1 second using
Thread.sleep(1000)inside a try-catch block.
Clock.java
import java.util.*;
class Clock {
public static void main(String[] a)
{
Date d = null;
while(true) {
d = new Date();
int x = d.getHours();
int y = d.getMinutes();
int z = d.getSeconds();
System.out.printf("%02d:%02d:%02d\r",x,y,z);
try {
Thread.sleep(1000);
}catch(Exception e) { }
}
}
}
Explanation of the Program
- The
Thread.sleep(milliseconds)method temporarily suspends the execution of the current thread for a specified duration. - By sleeping for 1000 milliseconds (1 second) in an infinite loop, we can simulate the ticking of a clock.
- The carriage return
\ris a console trick: it moves the cursor back to the beginning of the current line without moving down to the next line, causing the new time to seamlessly overwrite the old time.
Complexity
Time Complexity
O(1) - Infinite loop execution.
Space Complexity
O(1)