- System.exit() в Java – что это?
- Как вы выходите из функции в Java?
- Что такое метод System.exit()?
- Примеры
- Branching Statements
- The continue Statement
- The return Statement
- How to End a Java Program
- How to End a Java Program?
- How to End a Java Program Using System.exit() Method?
- How to End a Java Program Using return Statement?
- Conclusion
- About the author
- Farah Batool
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) или любое ненулевое значение – указывает на неудачное завершение.
Исключение: выдает исключение 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;ielse < System.out.println("Exit from the loop"); System.exit(0); //Terminates jvm >> > >
Вывод: array [0] = 1 array [1] = 2 array [2] = 3 array [3] = 4 Выход из цикла
Объяснение: В приведенной выше программе она печатает элементы до тех пор, пока условие не станет истинным. Как только условие становится ложным, оно печатает оператор и программа завершается.
Branching Statements
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for , while , or do-while loop, as shown in the following BreakDemo program:
class BreakDemo < public static void main(String[] args) < int[] arrayOfInts = < 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 >; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) < if (arrayOfInts[i] == searchfor) < foundIt = true; break; > > if (foundIt) < System.out.println("Found " + searchfor + " at index " + i); >else < System.out.println(searchfor + " not in the array"); >> >
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program’s output is:
An unlabeled break statement terminates the innermost switch , for , while , or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo , is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled «search»):
class BreakWithLabelDemo < public static void main(String[] args) < int[][] arrayOfInts = < < 32, 87, 3, 589 >, < 12, 1076, 2000, 8 >, < 622, 127, 77, 955 >>; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) < for (j = 0; j < arrayOfInts[i].length; j++) < if (arrayOfInts[i][j] == searchfor) < foundIt = true; break search; >> > if (foundIt) < System.out.println("Found " + searchfor + " at " + i + ", " + j); >else < System.out.println(searchfor + " not in the array"); >> >
This is the output of the program.
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for , while , or do-while loop. The unlabeled form skips to the end of the innermost loop’s body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String , counting the occurrences of the letter «p». If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a «p», the program increments the letter count.
class ContinueDemo < public static void main(String[] args) < String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) < // interested only in p's if (searchMe.charAt(i) != 'p') continue; // process p's numPs++; >System.out.println("Found " + numPs + " p's in the string."); > >
Here is the output of this program:
To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p’s instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo , uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo , uses the labeled form of continue to skip an iteration in the outer loop.
class ContinueWithLabelDemo < public static void main(String[] args) < String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i > foundIt = true; break test; > System.out.println(foundIt ? "Found it" : "Didn't find it"); > >
Here is the output from this program.
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn’t. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
The data type of the returned value must match the type of the method’s declared return value. When a method is declared void , use the form of return that doesn’t return a value.
The Classes and Objects lesson will cover everything you need to know about writing methods.
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.