Countdown Tutorial in Java

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

When working with time-sensitive tasks in Java, it's important to understand how to create and activate a timer. For example, you may want to give a user one minute to answer a question on a test and display how many seconds are remaining. You can use the built-in Java packages to create a timer that runs for a set amount of time and performs an action at regular intervals.


Step 1

Open your Java file in an editor, such as Eclipse, JBuilder X or Netbeans.

Video of the Day

Step 2

Import the necessary time classes at the top of your Java source file by adding the code:

import java.util.Timer; import java.util.TimerTask;


Step 3

Add a "CountDown" class after the "import" commands that performs a timer countdown by adding the code:

public class CountDown {

Timer timer;


public CountDown() { timer = new Timer(); timer.schedule(new DisplayCountdown(), 0, 1000); }

class DisplayCountdown extends TimerTask { int seconds = 60;



public static void main(String args[]) { System.out.println("Countdown Beginning"); new CountDown(); } }

Change the value in "int seconds = 60;" to however many seconds you want the countdown to run. Change "1000," which is milliseconds, in "timer.schedule(new DisplayCountdown(), 0, 1000);" if you want the countdown to to display countdown values more or less frequently than once a second. It will display, "Countdown Beginning," followed by "59 seconds remaining," "58 seconds remaining" and so on until it gets to 0, at which point it will display, "Countdown finished."

Step 4

Save the Java source file and compile and run the program to view your countdown timer.

Video of the Day




Report an Issue

screenshot of the current page

Screenshot loading...