where does the system.exit() goes to in Java?

1.8k views Asked by At

It seems this is one way to have a return status code from your main. but I am wondering where does this int go? I tried it on eclipse, But I do not see it on console. how do I get the status code

public static void main(String[] args){
         int status = 123;
          System.exit(status);
     }
5

There are 5 answers

12
Sotirios Delimanolis On BEST ANSWER

That value is known as the exit status

The exit status or return code of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task.

Here's a little Java test to demonstrate it

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Foo {
    public static void main(String[] args) throws Exception {
        if (args.length != 0)
            System.exit(Integer.parseInt(args[0]));
        ProcessBuilder builder = new ProcessBuilder(Arrays.asList("java", "Foo", "42"));
        Process process = builder.start();
        System.out.println(process .waitFor());     
    }
}

compile and run this program without any arguments. It will print

42

This java program starts a child process. When that process ends, it returns the value that was passed to it in System.exit(?) to its parent process which it then prints out.

0
Nic Robertson On

The exit code (status) is returned to the operating system on termination of the JVM so if you were to run it through terminal/command line you would see if the program terminated abnormally.

0
AudioBubble On

The exit code is usually returned to a script or program that is running your application, for instance, I wrote the following simple java program

class Test {

    public static void main(String[] args) {
        System.exit(123);
    }

}

I then compiled it using javac Test.java Next I wrote a simple bash script that would run java Test and then print out the exit code like this

#!/bin/bash

java Test
echo $?

And when i run the bash script the numbers 123 are printed to the screen, as $? is the exit code of the last command that was run.

0
Hot Licks On
C:\JavaTools>javac SystemExit.java

C:\JavaTools>java SystemExit

C:\JavaTools>echo %ERRORLEVEL%
123
0
Weibo Li On

The exit code will be returned to the OS. Return 0 means the program exits without an error and vice versa.

Return different error code means different causes. The could help the OS(or parent process) find out what's wrong with the program.