Home »
        Java Programs » 
        Java Basic Programs
    
    Java program to design a digital clock
    
    
    
    
        Write a Java program to design a digital clock.
        
            Submitted by Nidhi, on March 04, 2022
        
    
    
    Problem statement
    In this program, we will design a digital clock and print time.
    Java program to design a digital clock
    The source code to design a digital clock is given below. The given program is compiled and executed successfully.
// Java program to design a digital clock
public class Main {
  public static void main(String[] args) {
    int hour = 0;
    int minute = 0;
    int second = 0;
    try {
      while (true) {
        //clear output screen
        System.out.print("\033[H\033[2J");
        System.out.flush();
        System.out.printf("%02d : %02d : %02d ", hour, minute, second);
        second++;
        if (second == 60) {
          minute += 1;
          second = 0;
        }
        if (minute == 60) {
          hour += 1;
          minute = 0;
        }
        if (hour == 24) {
          hour = 0;
          minute = 0;
          second = 0;
        }
        Thread.sleep(1000);
      }
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}
Output
00 : 00 : 05
    Explanation
    In the above program, we created a public class Main. It contains a static method main().
    The main() method is an entry point for the program. Here, we printed the digital clock by updating the second value every 1 second.
	Java Basic Programs »
	
	
    
    
    
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement