Exiting java program exit command

System.exit() в Java – что это?

Java – язык программирования, имеющий множество приложений. При программировании для одного из этих приложений вы можете застрять на каком-то этапе этой программы. Что делать в этой ситуации? Есть ли способ выйти в этой самой точке? Если эти вопросы вас беспокоят, вы попали в нужное место.

Что вы можете сделать, это просто использовать метод System.exit(), который завершает текущую виртуальную машину Java, работающую в системе.

Как вы выходите из функции в Java?

Вы можете выйти из функции, используя метод java.lang.System.exit(). Этот метод завершает текущую запущенную виртуальную машину Java (JVM). Он принимает аргумент «код состояния», где ненулевой код состояния указывает на ненормальное завершение.

Если вы работаете с циклами Java или операторами switch, вы можете использовать операторы break, которые используются для прерывания / выхода только из цикла, а не всей программы.

Что такое метод System.exit()?

Метод System.exit() вызывает метод exit в классе Runtime. Это выходит из текущей программы, завершая виртуальную машину Java. Как определяет имя метода, метод exit() никогда ничего не возвращает.

Вызов System.exit (n) фактически эквивалентен вызову:

Функция System.exit имеет код состояния, который сообщает о завершении, например:

  • выход (0): указывает на успешное завершение.
  • выход (1) или выход (-1) или любое ненулевое значение – указывает на неудачное завершение.
Читайте также:  Time python засечь время

Исключение: выдает исключение SecurityException.

Примеры

package Edureka; import java.io.*; import java.util.*; public class ExampleProgram< public static void main(String[] args) < int arr[] = ; for (int i = 0; i < arr.length; i++) < if (arr[i] >= 4) < System.out.println("Exit from the loop"); System.exit(0); // Terminates JVM >else System.out.println("arr["+i+"] = " + arr[i]); > System.out.println("End of the Program"); > >

Выход: arr [0] = 1 arr [1] = 2 arr [2] = 3 Выход из цикла

Объяснение: В приведенной выше программе выполнение останавливается или выходит из цикла, как только он сталкивается с методом System.exit(). Он даже не печатает второй оператор печати, который говорит «Конец программы». Он просто завершает программу сам.

package Edureka; import java.io.*; import java.util.*; public class ExampleProgram< public static void main(String[] args) < int a[]= ; for(int i=0;i > > >

Вывод: array [0] = 1 array [1] = 2 array [2] = 3 array [3] = 4 Выход из цикла

Объяснение: В приведенной выше программе она печатает элементы до тех пор, пока условие не станет истинным. Как только условие становится ложным, оно печатает оператор и программа завершается.

Источник

How to End a Java Program

Java is one of the most popular programming languages. It can run any program on JVM (Java Virtual Machine). The program will terminate as JVM stops. Usually, Java programs terminate when they reach the end of the program; however, there are some situations where you may need to terminate a program during the execution of specific conditions. In such scenarios, end that particular program with the help of methods supported by Java.

This blog will teach you how to end a program in Java. So, keep reading!

How to End a Java Program?

In Java, you can end a program using:

Check out each of the mentioned methods one by one.

How to End a Java Program Using System.exit() Method?

You can end a Java program by using the “exit()” method of the Java “System” class. It terminates the currently running JVM.

To invoke the mentioned method, follow the given syntax:

Here, the System.exit() method has a parameter 0, which indicates that the program will terminate without any error.

Example 1: Printing Strings Before and After Ending a Java Program

In this example, we will terminate our program after printing one statement. In the main() method, we will first print a String “Java Programming” by using the System.out.println() method:

Then, we will call the exit() method of the System class to terminate our program:

Lastly, we will try to print another String:

As you can see, the “Java Programming language” string is not displayed because the JVM is terminated before the execution of this line:

Example 2: Ending a Java Program Based on Condition

We will now terminate our program based on the condition added in an “if” statement, within the “for” loop. Firstly, we will create an integer array of even numbers:

We will print out the array values till the array element is greater than or equal to 10. If the added condition is evaluated as “true”, the program will print the specified message and terminate:

for ( int i = 0 ; i < array1.length; i++ ) {
if ( array1 [ i ] > = 10 ) {
System.out.println ( «Program terminated due to exit() method» ) ;
System.exit ( 0 ) ;
}
else
System.out.println ( array1 [ i ] ) ;
}

After executing the “for” loop, the message “Exit…” in the main() method will not print on the console because the program exits before the execution of this line:

The output shows the program was terminated when the value of the array was greater than or equal to 10:

Let’s head towards the other method!

How to End a Java Program Using return Statement?

The “return” statement is mostly used to return a value to a function; otherwise, the void return statement will end the execution of the current method or function.

Add the keyword “return” to the point where you want to program executed to be stopped:

Now, we can check the examples with return statements to terminate a Java program.

Example 1: Ending main() Method Using return Statement

The “return” statement can terminate a Java program if it is the last statement executed within the main() method. If you add code after a return statement, the Java program may crash and throw an “Unreachable code” Exception because after running the return statement, no other line will be executed:

public static void main ( String [ ] args ) {
System.out.println ( «Java Programming» ) ;
return ;
System.out.println ( «Java Programming language» ) ;
}

Example 2: Adding return Statement in “if” Condition

In this example, we will terminate the Java program with the “return” statement added in the “if” condition. It will act the same as the System.exit() method.

Firstly, we will create an integer array of even numbers named “array1”:

Next, we will print the values of array and terminate the program when an elements gets greater than or equals to 15:

for ( int i = 0 ; i < array1.length; i++ ) {
if ( array1 [ i ] > = 15 ) {
System.out.println ( «Program Exit due to return statement» ) ;
return ;
}
else
System.out.println ( array1 [ i ] ) ;
}

The statement added in the main() method will not be executed because the Java program will end before that:

Output

We have provided all the necessary instructions for ending a Java program.

Conclusion

To end or terminate a program in Java, use the System.exit() method or a return statement. Both ways are helpful, but the most commonly used approach is the System.exit() method. The System.exit() method terminates the currently executing JVM, whereas the return statement is used to return values or stop the function execution. This blog discussed how to end or terminate a Java program.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Java How To Exit Program

Java How To Exit Program

In the realm of Java, exiting a program is a nuanced process. It’s not just about ending the process, but signaling the JVM, releasing resources, and ensuring a smooth termination. Explore the different commands and understand their impact on your Java program.

In the world of Java, exiting a program is like saying goodbye at a party. You don’t just vanish into thin air (unless you’re a magician, of course). You need to signal your departure, and in Java, this is done using specific exit commands.

Important disclosure: we’re proud affiliates of some tools mentioned in this guide. If you click an affiliate link and subsequently make a purchase, we will earn a small commission at no additional cost to you (you pay nothing extra). For more information, read our affiliate disclosure.

The Exit Command: Your Golden Ticket Out

Think of the exit command as your golden ticket out of the program. It’s like telling the Java Virtual Machine (JVM), «Hey, I’m done here. You can shut down now.» The JVM, being the obedient entity it is, will then proceed to shut down, releasing all resources and effectively ending the program.

In this line of code, System.exit(0); is the equivalent of saying «I’m out». The 0 here is the status code that’s returned to the invoking process. A 0 typically means the termination was successful, while any other number indicates an abnormal termination.

The Abrupt Goodbye: Runtime.getRuntime().halt(0)

Now, if System.exit(0); is the polite way of saying goodbye, Runtime.getRuntime().halt(0); is the equivalent of abruptly leaving the party without saying a word. It’s a more forceful exit and doesn’t care about cleaning up or running any shutdown hooks. It’s like flipping the power switch off without shutting down your computer properly.

The Graceful Exit: System.runFinalization()

Then there’s the graceful exit, System.runFinalization() . This is like saying goodbye, cleaning up after yourself, and making sure everything is in order before you leave. It runs the finalization methods of any objects pending finalization.

The Exit Stage Left: Runtime.getRuntime().exit(0)

Lastly, there’s Runtime.getRuntime().exit(0); which is similar to System.exit(0); but it’s like exiting stage left instead of right. It’s another way of signaling the JVM to terminate.

Источник

Оцените статью