How do you keep the console from closing after the program is done in Java?
-
Im using IntelliJ IDEA, but I will compile application to jar file – mikigal Oct 30 '15 at 16:41
-
2Set a breakpoint on the last closing brace of the `main()`? – Sergey Kalinichenko Oct 30 '15 at 16:42
-
its dont working. I need code – mikigal Oct 30 '15 at 16:46
-
Ok, are you running the class in IntelliJ and expecting some output on IntelliJ console? Or you are running the jar using perhaps windows Command prompt? – Aragorn Oct 30 '15 at 16:56
4 Answers
readLine()
waits until you press a key:
public static void main (String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
in.readLine();
}

- 27,862
- 20
- 113
- 121
The simplest way I've found:
Scanner scanner = new Scanner(System.in);
scanner.nextLine();

- 331
- 5
- 13
There are several ways to achieve this.
You can request the user for input at the end of your
main
method.You can create and start a thread. Deamon threads are automatically closed when your main method finishes. However non-deamon threads will keep your application alive until they are finished.
Or just call
wait
on an object.
I'm not sure though, why you would want to keep an application alive, if it's not doing anything anymore.
Using a non-deamon thread:
// example of an application that never closes.
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public synchronized void run() {
for(;;)
try {
wait();
} catch (InterruptedException e) {
}
}
}).run();
}
Calling wait on an object:
public static void main(String[] args)throws Exception {
Object o = new Object();
synchronized (o) {
o.wait();
}
}

- 22,839
- 10
- 110
- 123
Firing empty Scanner
input at the end of the code works each time, because the scanner waits for user to press ENTER.
//to-do your code
Scanner.nextLine();
Shame Java does not have inbuilt wait or pause command for the console apps.
EDIT: If you want to construct Scanner, you do it like this:
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
System.in
is parameter that tells the scanner which input stream to use.

- 344
- 3
- 20
-
-
I have code: Scanner pause = new Scanner(""); pause.nextLine(); But I have crash Exception in thread "main" java.util.NoSuchElementException: No line found – mikigal Oct 30 '15 at 16:51