Countdown Tutorial in Java

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

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

Step

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

Step

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

Step

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

Step

public class CountDown {

Step

Timer timer;

Step

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

Step

class DisplayCountdown extends TimerTask { int seconds = 60;

Step

}

Step

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

Step

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

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