Java main return exit

Java Exit Program — How to end program in java?

Twitter Facebook Google Pinterest

A quick guide to exit program in java. Use System.exit() or return to end and terminate the java programs.

1. Overview

In this tutorial, We’ll learn how many ways to end java program and how to terminate program execution in java.

How to end program in java?

2. End and Terminate program using System.exit()

Use System.exit() method to end the java program execution. exit() method is from the System class and exit() is a static method.

System.exit() method gives the instructions to JVM to terminate the current running program from the point of exit() method.

package com.javaprogramto.programs.exit; public class JavaProgramExitExample < public static void main(String[] args) < System.out.println("hello java developers "); System.out.println("understand how System.exit() method works"); System.exit(0); System.out.println("Last line from this program"); >>
hello java developers understand how System.exit() method works Process finished with exit code 0

From the above code, we expect the 3 statement to be printed on the console from three System.out.println() statements But it has prinited only first two.

Because System.exit() is after the second sysout. Wheneven java runtime finds exit() method, it just stops the program execution at any point of time.

0 value indicates to jvm exit the program with successful finishing with no errors. That is graceful termination.

but if you pass any non zero value leads to print with the error message. But from java 8 or above versions, it does not show any error message even if non zero value is pased.

System.exit(2); System.exit(-1); System.exit(3);

3. Java end program using return statement

We can use return statements from the methods or from the main program to end the current method execution and continue from its parent.

package com.javaprogramto.programs.exit; public class JavaProgramExitExample2 < public static void main(String[] args) < System.out.println("satement 1"); System.out.println("statement before return statement"); return; System.out.println("Last line from this program"); >>

This program does not compile because there is a sysout statement after return statement. That mean compiler detects that last line of the program is never going to be executed with the error message «Unreachable code«.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code at com.javaprogramto.programs.exit.JavaProgramExitExample2.main(JavaProgramExitExample2.java:12)
package com.javaprogramto.programs.exit; public class JavaProgramExitExample3 < public static void main(String[] args) < System.out.println("first line from main method"); method(); System.out.println("last line from main method"); >private static void method() < System.out.println("executing the method"); return; >>
first line from main method executing the method last line from main method

4. Java end program using return statement with if else

If the condition is met then execute the logic and return «even number» and from else condition return «odd number» value.

package com.javaprogramto.programs.exit; public class JavaProgramExitExample4 < public static void main(String[] args) < System.out.println("first line from main method"); int number = 10; String value = getValue(number); System.out.println(value); System.out.println("last line from main method"); >private static String getValue(int number) < System.out.println("statement 1"); if(number % 2 == 0) < return "even number"; >else < return "odd number"; >> >
first line from main method statement 1 even number last line from main method

5. Conclusion

In this article, we’ve seen how to end the program in java using System.exit() and return statement.

Читайте также:  Css v34 сервера джайл

In the real time, system.exit() is used in the standalone and concurrent applications on the particular conditions met. But, prefer to throw the custom exception with the correct error message for better debugging.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

A quick guide to exit program in java. Use System.exit() or return to end and terminate the java programs.

Источник

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!

Читайте также:  Javascript выбрать значение select

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.

Читайте также:  Java stream delete element

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.

Источник

How to end program in java

How to end program in java

Ho In this post, we will see how to end program in java.

You can use System.exit(0) to end program in java.

Using System.exit() to end java program

You can use exit() method of System class to end java program.

System.exit() causes Java virtual machine to exit and terminate the current process. You can call System.exit() anywhere in the program, resulting in JVM termination.

As System.exit() is the static method of System class, the compiler does not know what it will do, hence does not give unreachable code error.

If we pass 0 to System.exit() method, it indicates that termination happened successfully and pass this value to operating system.

  • exit(0) : It indicates successful end of java program.
  • exit(-1) or exit(1) or exit(any non zero value) : It indicates unsuccessful end of java program.

Example to demonstrate System.exit() method

As you can see, it did not print After calling Syste.exit() after calling System.exit() method.

How to end java program in an if statement in java

You can exit program in java based on if statement condition.
Here is an example.

As you can see, program ended as soon as array element was greater or equals to 40 while iterating. It neither continued the loop nor printed Loop ends here after calling System.exit() method.

Using return to end current method

If you just want to exit from current method, you can use return statement.

return statement stops the execution of current method and return it to calling method. It is a reserved keyword which compiler already knows.

return can end java program if it is the last statement inside main method of class being executed. If you put code after a return statement, compiler will give error about unreachable code.

Источник

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