Terminating a Java Program
Calling System.exit(0)
(or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java
process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in System
class, the compiler does not know what it will do - and hence does not complain about unreachable code.
return
statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void
(as in your example), then you do not need to specify a value, as you'd need to return void
. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.
return
would cause the program to exit only if it's inside the main
method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:
public static void main(String... str) {
System.out.println(1);
return;
System.out.println(2);
System.exit(0);
}
will not compile with most compiler - producing unreachable code
error pointing to the second System.out.println
call.
How to quit a java app from within the program
You can use System.exit()
for this purpose.
According to oracle's Java 8 documentation:
public static void exit(int status)
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 call
System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
Schedule top / terminate a Java program on a specific time
You can use TimerTask to do that, here is an example:
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class StopApp {
Timer timer = new Timer();
TimerTask StopApp = new TimerTask() {
@Override
public void run() {
System.exit(0);
}
};
public StopApp() {
//timer.schedule(exitApp, getDateDiff(new Date("get the actual time"), new Date("get the time you want to stop your app"), TimeUnit.SECONDS));
//Example
timer.schedule(StopApp, new Date(System.currentTimeMillis()+2*1000));//Exits after 2 sec of starting the app
while(true)
System.out.println("The App still turn");
}
public static Date getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
Date date=new Date(diffInMillies);
return date;//timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
new StopApp();
}
}
New To Java (Program Keeps Terminating)
Like said, you are testing if Scanner object equals to String instance, which is never true, as they are completely different kinds of objects.
You'd want to replace this:
Scanner input=new Scanner(System.in);
// printing here
if (input.equals(...
with this:
Scanner scanner = new Scanner(System.in);
// printing here
String input = scanner.nextLine();
if (input.equals(...
Addition: of course when you do that, you also need to change other references like
double size = input.nextInt();
to use your scanner instance:
double size = scanner.nextInt();
Terminate a java program A with a java program B
If you want to program to terminate or stop, just type in
System.exit(0);
Although System.exit(1);
will indicate that a "non-zero" exit code occurred which usually means something wrong happened. User 0 if it exits and everything is fine. Use non-zero (like 1) to indicate that there was an error (like a non-existent file or something).
If you want to stop the java program from another java program, you first have to get the process id of the java program. Once this process ID is known, you can kill it with a system call (just like you would in a terminal).
For example, if I had this Java program running indefinitly:
import java.lang.management.ManagementFactory;
public class Test {
public static void main(String[] args) {
System.out.println("Hello, World");
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
while (true) {
int i = 0;
}
}
}
I could see it's process ID (for example 123
) and kill it with the following command.
$ kill 123
Once this is done, you have to find some way for it to output this data to another java program after it asks for it. Then once the process ID is known, you would administer a system call or shell exec.
import java.lang.* ;
public class Shell
{
public static void main(String[] args)
{
try {
String cmd = "kill 123";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd) ;
} catch (Exception ex) {
System.out.println("SOMETHING WENT WRONG");
}
}
}
Node that all shell commands or run.exec
must catch the exception since it is thrown. It must be in a try catch block or it won't compile.
Hope this helps.
Related Topics
Why Are Class Static Methods Inherited But Not Interface Static Methods
Remove Last Character of a Stringbuilder
Why Does Java Switch on Contiguous Ints Appear to Run Faster with Added Cases
How to Convert .Pfx File to Keystore with Private Key
@Generatedvalue Polymorphic Abstract Superclass Over MySQL
Java Naming Convention with Acronyms
Is -Djava.Library.Path=... Equivalent to System.Setproperty("Java.Library.Path", ...)
Java Getting an Error for Implementing Interface Method with Weaker Access
How to Debug a Multi-Threaded App in Intellij
Why Maven? What Are the Benefits
Compareto with Primitives -> Integer/Int
Java File - Open a File and Write to It
How to Get an Enum Based on the Value of Its Field
@Onetomany List<> VS Set<> Difference
How to Run a Java Class in a Package
Why Shouldn't Java Enum Literals Be Able to Have Generic Type Parameters
Why Does the New Java 8 Date Time API Not Have Nanosecond Precision