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 1

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

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 void run() {
  if (seconds > 0) {
    System.out.println(seconds + " seconds remaining");
    seconds--;
  } else {
    System.out.println("Countdown finished");
    System.exit(0);
  }
}

}

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.

references