0
  1. Can System.exit() be used at sentinel value?

  2. If not what purpose would System.exit() provide?

  3. If this code is in a loop and is entered, would it exit?

 String day;
 day = JOptionPane.showInputDialog("what is todays date");
 JOptionPane.showMessageDialog(null,"Today is: " + day);
 System.exit(1);
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263

3 Answers3

1

1.Can system.exit() be used at sentinel value?

Why would you want to use it as sentinel values? You probably can't use it as a loop guard in your loop, because once exited, your program terminates.

Secondly, if there is any unfinished task, your program will terminate abruptly.

If not what purpose would 2.system.exit() provide?

You may look at this post regarding Java's System.exit(): Java's System.exit(0); vs C++ return 0;

3.if this code is in a loop and they enter 1. Would it exit?

Your code will exit eventually no matter what is being entered. It will not only exit the loop, it will terminate your program. To jump out of a loop, you use break and not System.exit().

To skip the rest of code in a loop, you use continue.

Community
  • 1
  • 1
user3437460
  • 17,253
  • 15
  • 58
  • 106
0

In order of appearance:

  1. No, you cannot use System.exit(status) as sentinel value because it isn't a value, it's a method call;
  2. System.exit(int status) exits the application and Virtual Machine, ending all threads and returning the status code to the calling application or terminal;
  3. Yes, the thread that calls the System.exit method will not execute any code that appears after the call, and the VM will be terminated.

Note that the compiler will not treat the call to System.exit(int status) as exit point of the code block it is in. That means that you may get compiler errors that would not be present if you would throw an exception, use break, continue or return instead. Compilers don't know what System.exit(int status) does, it just treats it as any other method call.

To exit a loop you should use break or make use of a boolean condition within while or for (after the first ; character).

Usually System.exit() is only called if the application needs to terminate early, returning an error code other than 0. Normally the application exits with status code 0 when all the (non-deamon) threads have finished. This is usually when the main method is exited in a application that doesn't perform multithreading (GUI applications usually do perform multithreading).

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
0

Any flow should never be derived from System.exit() .

you have various other mode exit from a program

return , continue , break or even u can throw logical exception which also let you know the state of program.

Zuned Ahmed
  • 1,357
  • 6
  • 29
  • 56