What is System.exit() in JAVA ?

  In Java, System.exit() is a command used to immediately shut down the running program.

Think of it like a "Kill Switch" or an emergency exit button for your code. Once this line is reached, the program stops everything it is doing and closes, even if there is more code left to run.

How it Works
When you call System.exit(n), you must provide an integer (usually 0 or 1) inside the parentheses. This is called a Status Code: 
  • System.exit(0): Tells the computer, "The program finished successfully with no problems.
  • System.exit(1) (or any non-zero number): Tells the computer, "The program crashed or stopped because of an error.
Layman's Example: The ATM
Imagine you are writing code for an ATM machine.
  1. The user inserts a card.
  2. The user enters the wrong PIN three times.
  3. For security, you want the program to stop immediately so no one can try a fourth time.
Example:

if (failedAttempts == 5) {
    System.out.println("LOCKDOWN ACTIVATED.");
    System.exit(1); // The program "dies" here. Nothing below this line runs.
}

Why not use it all the time?
It is a "brute force" move. Because it kills the program instantly, it might not give the program time to save a file or close a connection to a database. It’s effective, but it’s the "nuclear option."
For deeper technical specifics on how the Virtual Machine handles this, you can check the Java SE Specifications.

Comments

Popular posts from this blog

GenAI in QA Automation: Game Changer or Just Hype?

How to choose the right QA Automation tool for your web application?

How to validate broken link on the webpage using playwright?