JAVA , System.exit() ? How do i use it?

5.5k views Asked by At

I've been learning java for some months now and i came through this:

System.exit(value);

I think you can use it to test your code depending on what "value" you give to it.

e.g if i want to check if a loop was used or worked as it should , i may do:

if(value == 1)
{
    System.out.println("Hi");
    System.exit(0);
}

But after a bit of testing it came out that i actually cant se the "value" after the loop executed.

Am I thinking of this right? Is there any other use of this code?

6

There are 6 answers

2
Mureinik On BEST ANSWER

System.exit(value) terminates the JVM and uses value as the return value of the process. So, for instance, in *nix systems, you could use:

$ echo `java MyJavaClass`  
4
AudioBubble On

The documentation would (as usual) help a lot -.- . System.exit terminates the JVM.

0
GregH On

The java.lang.System.exit() method terminates the currently running Java Virtual Machine.

The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

Likewise, a 0 status code returns a normal termination;

System.exit(0) //exit signaling the process terminated successfully

System.exit(-1) //exit signaling the process did not terminate successfully
0
Amir Afghani On
System.exit(value)

will cause the program to terminate with the given value. Traditionally (on unix systems at least), 0 has been designated as the numeric value that will indicate successful execution of a program. All non-zero values indicate a failure mode that the calling environment will know how to interpret.

I think you can use it to test your code depending on what "value" you give to it.

I wouldn't use this methodology to test my code. Instead consider writing unit tests to test your code.

0
Suresh Parmar On

System.exit() Method can be use to terminate program so when you use this method it will terminate program as it reached to parameter value of System.exit() method.

0
Patricia Shanahan On

To check the exit code in Eclipse, switch to the "Debug" view. For example, immediately after running:

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

the top left window in the Debug view contains:

<terminated>Test [Java Application] 
    <terminated, exit value: 55>C:\Program Files\Java\jre1.8.0_31\bin\javaw.exe (Jun 17, 2015, 11:21:15 AM)