Ask coding questions

← Back to all posts
How can I delay something in Java?
PythoNinja (2)

I want something to delay in Java, but I don't know how....
Thanks!

Answered by Coder100 (18904) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (18904)

Use the thread.sleep method.
https://www.tutorialspoint.com/java/lang/thread_sleep_millis.htm

import java.lang.Thread;

public class Main {
  public static void main(String[] args) {
    System.out.println("Hi");
    Thread.sleep(1000);
    System.out.println("hi after 1 second");
  }
}
PythoNinja (2)

@Coder100 It says "Unhandled exception type InterruptedExecption" when I did the stuff.

Coder100 (18904)

@PythoNinja send repl that's not supposed to happen

PythoNinja (2)

@Coder100 Now it says this instead:

Coder100 (18904)

@PythoNinja

public class main(String[] args) throws InterruptedException

change that line to that

PythoNinja (2)

@Coder100 Okay, I changed my Main Class into the public class main, and now, it says

for some reason.

Coder100 (18904)

uh can you invite me you did it wrong @PythoNinja

cuber1515 (91)

I believe you do Thread.sleep() and in the parenthesis put the milliseconds, so if you wanted to do it for 1 second, then: Thread.sleep(1000).