JAVA Syllabus
QUESTIONS & ANSWERS

What is the difference between return and System.exit(0)?

return and System.exit(0) are two ways of terminating the execution of a program in different ways:

  1. return: return is a keyword used in a method to indicate that the method has finished executing and the control is returned back to the caller of the method. The return statement can be used to return a value or simply indicate that the method has finished executing.

For example:

public int add(int a, int b) {
   int result = a + b;
   return result;
}

In the above example, the method add() takes two integers as arguments, adds them and returns the result.

  1. System.exit(0): System.exit(0) is a method provided by the Java Runtime Environment (JRE) that terminates the currently running Java Virtual Machine (JVM) with an exit status of 0. This method is typically used to terminate a program when it encounters an error that cannot be handled or to force the termination of a program.

For example:

public static void main(String[] args) {
   // Perform some calculations
   // If an error occurs, terminate the program with an exit status of 1
   if (error) {
      System.exit(1);
   }
   // Otherwise, continue executing the program
}

In the above example, the main method checks for an error and if an error occurs, it terminates the program with an exit status of 1. If the error does not occur, the program continues executing.

In summary, return is used to return control back to the calling method with a value, while System.exit(0) is used to terminate the program abruptly with an exit status of 0 or an error code.

04/03/2023, 12:49 pm Read : 94 times