Close code in java

How to Close an Application Properly

In order to close Java program we need to consider which kind of Java application is it?, because termination of Java application varies between normal core java program to swing GUI application. In general all Java programs terminate automatically once all user threads created by program finishes its execution, including main thread.

1. Introduction

JVM doesn’t wait for daemon thread so as soon as last user thread finished, Java program will terminate. If you want to close or terminate your java application before this, your only option is to use System.exit(int status) or Runtime.getRuntime().exit() . This cause JVM to abandon all threads and exit immediately. Shutdown hooks are get called to allow some last minute clearing before JVM actually terminates. System.exit() also accept an int status parameter where a non zero value denote abnormal execute and the result returned by java command to caller. In this java tutorial we will see example of closing both Java program and Java Swing application.
Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT) . JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way.

2. Java Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API

2.1 MVC Architecture

  • A Model represents component’s data.
  • View represents visual representation of the component’s data.
  • Controller takes the input from the user on the view and reflects the changes in Component’s data.
  • Swing component have Model as a seperate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Every user interface considers the following three main aspects:

  • UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
  • Behavior: These are events which occur when the user interacts with UI elements.

2.2 Swing Features

  • Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
  • Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
  • Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.
Читайте также:  Processing arrays in java

2.3 Setup

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work.

3. Example of Closing Java program using System.exit()

Here is a code example of closing Java program by calling System.exit() method. Remember non zero argument to exit() method like exit(1) denotes abnormal termination of Java application.

import java.util.logging.Level; import java.util.logging.Logger; /** *Java program which terminates itself by using System.exit() method , non zero call to exit() method denotes abnormal termination. */ public class JavaCloseExample < public static void main(String args[]) throws InterruptedException < Thread t = new Thread()< @Override public void run()< while(true)< System.out.println("User thread is running"); try < Thread.sleep(100); >catch (InterruptedException ex) < Logger.getLogger(JavaCloseExample.class.getName()).log(Level.SEVERE, null, ex); >> > >; t.start(); Thread.sleep(200); System.out.println("terminating or closing java program"); System.exit(1); //non zero value to exit says abnormal termination of JVM > > Output: User thread is running User thread is running terminating or closing java program Java Result: 1 //1 is what we passed to exit() method

This Java program first creates a Thread in main method and start it, which prints “User thread is running” and then main thread sleeps for 200 Milli second. Till then, the other user thread is running and printing but once the main thread wakes up, it terminates the program by calling exit() method of java.lang.System class.

3.2 How to close Java swing application from program

Swing application mostly uses JFrame as top level container which provides two option to close swing GUI application from code. First option which is default is EXIT_ON_CLOSE which terminates Java swing GUI program when you click close button on JFrame window. Another option is DISPOSE_ON_CLOSE which terminates JVM if last displayable window is disposed off.

Difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE is that if you have a non daemon thread running it will not be closed in case of DISPOSE_ON_CLOSE , while EXIT_ON_CLOSE terminate JVM even if user thread is running. Run the below example by un comment DISPOSE_ON_CLOSE in your IDE and you can see user thread running even after clicking on close button. Here is a complete code example of closing Swing application in Java.

import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; /** * Java swing program which terminates itself by calling EXIT_ON_CLOSE and DISPOSE_ON_CLOSE */ public class CloseSwingExample < public static void main(String args[]) throws InterruptedException < JFrame frame = new JFrame("Sample"); //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); won't terminate JVM if user thread running frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); Thread t = new Thread() < @Override public void run() < while (true) < System.out.println("User thread is running"); try < Thread.sleep(100); >catch (InterruptedException ex) < Logger.getLogger(CloseSwingExample.class.getName()).log(Level.SEVERE, null, ex); >> > >; t.start(); > >

3.3 Important Points for closing or terminating a Java application

  • System.exit() actually calls Runtime.getRuntime().exit() method.
  • Non zero argument to exit() denotes abnormal termination of Java program.
  • Shutdown hooks are executed before Java program actually terminates.
  • There are two options to close Java Swing application one is EXIT_ON_CLOSE and other is DISPOSE_ON_CLOSE .
  • DISPOSE_ON_CLOSE doesn’t terminate JVM if any user thread is running.
  • You can also implement window listener to implement your closing mechanism by using System.exit() in Swing application.
Читайте также:  Hidden space in html

That’s all on how to close or terminate Java program. We have also seen example of closing Swing application in Java and difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE .

4. Download The Source Code

This was an example of closing a Java application properly.

Источник

How to Close Java Program or Swing Application with Example

In order to close the Java program, we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java programs to swing GUI applications. In general, all Java program terminates automatically once all user threads created by program finishes its execution, including main thread. JVM doesn’t wait for the daemon thread so as soon as the last user thread is finished, the Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit().

This causes JVM to abandon all threads and exit immediately. Shutdown hooks are get called to allow some last-minute clearing before JVM actually terminates. System.exit() also accept an int status parameter where a non-zero value denotes abnormal execution and its result returned by java command to the caller.

In this java tutorial, we will see an example of closing both the Java program and the Java Swing application. This is also a good swing interview question that you can ask any GUI developer and my second article in the swing after writing invokeAndWait vs invokeLater

1. Example of Closing Java program using System.exit()

Here is a code example of closing the Java program by calling System.exit() method. Remember non zero arguments to exit() method like exit(1) denotes abnormal termination of Java application.

import java.util.logging.Level ;
import java.util.logging.Logger ;

/**
*Java program which terminates itself by using System.exit() method , non zero call to exit() method denotes abnormal termination.
*/

public class JavaCloseExample

public static void main ( String args []) throws InterruptedException

Thread t = new Thread () <
@Override
public void run () <
while ( true ) <
System. out . println ( «User thread is running» ) ;
try <
Thread. sleep ( 100 ) ;
> catch ( InterruptedException ex ) <
Logger. getLogger ( JavaCloseExample. class . getName ()) . log ( Level. SEVERE , null , ex ) ;
>
>
>
> ;

t. start () ;
Thread. sleep ( 200 ) ;
System. out . println ( «terminating or closing java program» ) ;
System. exit ( 1 ) ; //non zero value to exit says abnormal termination of JVM
>
>

Output:
User thread is running
User thread is running
terminating or closing java program
Java Result: 1 //1 is what we passed to exit() method

This Java program first creates a Thread in the main method and start it which prints “ User thread is running ” and then main thread sleep for 200 Millisecond, till then other user thread is running and printing but once main thread woken up it terminates the program by calling exit() method of java.lang . System class.

Читайте также:  Jre java exe path

2. How to close Java swing application from the program

Swing application mostly uses JFrame as a top-level container which provides two options to close swing GUI application from code. The first option which is the default is EXIT_ON_CLOSE which terminates the Java swing GUI program when you click the close button on the JFrame window.

Another option is DISPOSE_ON_CLOSE which terminates JVM if the last displayable window is disposed of. Difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE is that if you have a non-daemon thread running it will not be closed in case of DISPOSE_ON_CLOSE , while EXIT_ON_CLOSE terminate JVM even if user thread is running.

Run the below example by uncommenting DISPOSE_ON_CLOSE in your IDE and you can see user thread running even after clicking on the close button. here is a complete code example of closing the Swing application in Java.

import java.util.logging.Level ;
import java.util.logging.Logger ;
import javax.swing.JFrame ;

/**
* Java swing program which terminates itself by calling EXIT_ON_CLOSE and DISPOSE_ON_CLOSE
*/

public class CloseSwingExample

public static void main ( String args []) throws InterruptedException

JFrame frame = new JFrame ( «Sample» ) ;
//frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); won’t terminate JVM if user thread running
frame. setDefaultCloseOperation ( JFrame. EXIT_ON_CLOSE ) ;
frame. setSize ( 200 , 200 ) ;
frame. setVisible ( true ) ;

Thread t = new Thread ()

@Override
public void run () <
while ( true ) <
System. out . println ( «User thread is running» ) ;
try <
Thread. sleep ( 100 ) ;
> catch ( InterruptedException ex ) <
Logger. getLogger ( CloseSwingExample. class . getName ()) . log ( Level. SEVERE , null , ex ) ;
>
>
>
> ;

Источник

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.

Источник

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