How to Add Delays or Pauses in Java

As a programmer, you may sometimes need your application to pause for a set time or until the user presses a key. You can order the thread to sleep and yield its processor time to the operating system and other programs for a set time. On the other hand, the easiest way to pause while waiting for a keystroke is just to read the keystroke and discard it. This also has the effect of pausing the program to wait for user input.

Step

Open Netbeans or your favorite Java Integrated Development Environment, or IDE.

Step

Create a new class by clicking "File" and "New Class." Name it "PauseTester."

Step

Type "psvm" and Netbeans expands this into a valid "main" method for you.

Step

Type the following code into the "main" method:

Step

System.out.print("I am waiting..."); Thread.sleep(3000); System.out.println("DONE."); System.out.println("Press any key to end the program."); System.in.read();

Step

Two different methods are being combined here to pause the program. First, Java prints a message and sleeps for three seconds -- 3,000 milliseconds -- before printing a "DONE" message. Next, Java asks the user to press a key, and "System.in" waits until it reads a single byte of data from the keyboard. Normally, you could get the key value from "System.in," but if your goal is simply to pause, then you don't care what key is pressed.

Step

Click "Run."