How to Exit a Java Program with an Exit Code
Every program ends with an exit code: 0 when it succeeded, anything else when it didn't. Shells, scripts and CI jobs read that number to decide what happens next. In Java, System.exit(1) ends the program and reports a failure.
Syntax
System.exit(<status>);
| Part | What it does |
|---|---|
System.exit | Shuts the Java Virtual Machine down; the code after it never runs. |
<status> | The exit code: 0 for success, a non-zero number such as 1 for failure. |
The JDK 25 documentation for System.exit: "The argument serves as a status code. By convention, a nonzero status code indicates abnormal termination." It adds that the method "neither returns nor throws an exception".
The Example
The example checks whether all orders are paid. They aren't, so it prints an error and exits with code 1.
Prerequisites
- A JDK, the Java Development Kit.
java Main.javaruns a single file without compiling it first. This guide uses OpenJDK 25.0.5.1.
Step 1: Write the Code
Create a file named Main.java:

public class Main {
public static void main(String[] args) {
boolean allPaid = false;
if (!allPaid) {
System.err.println("Some orders are not paid.");
System.exit(1);
}
System.out.println("All orders are paid.");
}
}
Step 2: Run It and Read the Exit Code
Run the program, then ask the shell for the exit code of the last command:
- macOS / Linux
- Windows (PowerShell)
java Main.java
echo $?

java Main.java
$LASTEXITCODE

Some orders are not paid.
1
The last line of main never ran, and the shell reported 1, so a script or CI job knows the check failed.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Printing an error but ending normally | The exit code is 0, so a CI job carries on | Call System.exit(1) on failure |
Calling System.exit deep inside library code | The whole program stops, which callers can't prevent | Throw an exception there and exit only in main |
Reading $? after another command | It now holds that command's code | Read it right after running the program |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
echo $? prints 0 after an error message | The program never called System.exit with a non-zero code | Exit with 1 on failure |
$LASTEXITCODE is empty | No program has run yet in this PowerShell window | Run the program first |
FAQ
What exit code does an uncaught exception give?
1. A program that ended with an uncaught NumberFormatException printed the stack trace and exited with code 1.
What does main returning normally give?
0, unless some code called System.exit with another number.
Conclusion
System.exit(1) ends a Java program with a failure code that the shell reads as $? in zsh or bash and $LASTEXITCODE in PowerShell. Keep the call in main, where the program's end is easy to see.
Additional Resources
- System.exit(int), in the JDK 25 API documentation.
