Search code examples
javajoptionpane

Program doesn't terminate when reaching the end of the main method


I have a program where I ask for an input from the user before I launch it.

public static void main(String args[]) 
{
    String database = JOptionPane.showInputDialog(new JFrame(), "Enter a DB:");
    if(database!=null && database.foundInDB()) {
        SPVerification spv = new SPVerification();
        spv.setVisible(true);
    }
    //System.exit(1);  Without it the program doesn't terminate although it's the end
    //                 of the main function.                  
}

If the user enters a database that's not found, the program shouldn't be executed.

When I enter a wrong DB name, the code below if statement doesn't execute, so I reach the end of the main method, but the program doesn't terminate, but if I add system.exit(1) after the if statement, the program terminates. Why do I need to call System.exit(1) although I've reached the end of main?


Solution

  • You have created a new JFrame which, by default, will not close as there is nothing to trigger the window to be disposed such as a WindowEvent. As this appears to be a non-UI based application, you could simply use:

    JOptionPane.showInputDialog(null, "Enter a DB:");