Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to create count-down timer.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to create count-down timer.

Objective

Write a Java program to create a single-digit console count-down timer using backspace.

Algorithm / Approach

  1. Create a loop starting at 9 and going down to 0.
  2. Inside the loop, print \b (Backspace) followed by the current number.
  3. Call Thread.sleep(1000) to pause for 1 second.
  4. Once the loop ends, print the final message.
CountDown.java
class CountDown {
 public static void main(String [] ar)
 throws Exception {
  int i = 9;
  while(i!=0){
   System.out.print("\b"+i);
   i--;
   Thread.sleep(1000); 
  }
  System.out.println("\b****************");
  System.out.println(" HAPPY BIRTHDAY "); 
  System.out.println("****************");
 }
}

Expected Output

//after count-down
//from 9 to 0
****************
 HAPPY BIRTHDAY
****************

Explanation of the Program

  • The \b character is an escape sequence for Backspace. It moves the terminal cursor back one space.
  • By printing a backspace and immediately printing the next number, we overwrite the previous number on the exact same spot in the terminal, creating the illusion of a digital countdown timer.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT