1

What is the use of System.exit()? What happens if I don't use it? My professor used it in the following way:

 public static void main(String[] args) throws Exception {

    // make sure that you have the right number of arguments
    if (args.length != 1) {
      System.out.println("Usage: java FileDemo filename");
      System.exit(0);
    }

I don't know why he used it. Also I don't get why he asked me to make sure that I have right number of arguments. How does he know if (args.length !=1) ? We have not yet populated String [] args in the main method.

Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
Elijah Dayan
  • 442
  • 6
  • 19

4 Answers4

2

The argument for args are supplied from the command-line (or if you use an IDE you can set the command-line arguments yourself through the GUI). So they are set regardless if you don't see them "in the code".

The docs of System.exit say (boldface mine):

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The usage in your program is kind-of irrelevant, because main will exit anyway when it finishes executing. But your professor probably wanted to demonstrate the correct action when the user supplied an incorrect number of arguments to the program. In that case, you want to free all the resources and exit gracefully. In that case using System.exit is perfectly fine.

Idos
  • 15,053
  • 14
  • 60
  • 75
0

String[] args is automatically populated by the JVM when called via the command line with arguments.

The answer to your second question lies here

Community
  • 1
  • 1
Joseph Young
  • 2,758
  • 12
  • 23
0

The String[] args is command line arguments to the program, and specified as part of a Java programs' entry point. System.exit(int) is used to terminate the running JVM and returns 0 to the parent process.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

The args[] array is the list of args pushed into the application from the outside. In your case the program just expect exactly 1 argument. When there is no or there is more than 1 the program just terminates. Here the System.exit(x) is just the termination cause the program seems not be started/used in the right way, normally your program would trigger the help function and print hints for the right usage. A "return;" would do the same thing, just ending the program.

Henning Luther
  • 2,067
  • 15
  • 22