System exit method in Java

0 votes

How does System.exit() method affect a program?

public class TestExit
{      
    public static void main(String[] args)
    { 
        System.out.println("hello world");

        System.exit(0);
    }      
}

Is it necessary to include this method in my code? Please explain.

Sep 28, 2018 in Java by 93.lynn
• 1,600 points
1,953 views

1 answer to this question.

0 votes

System.exit() is a method of System class and is used to execute the shutdown hooks before the program quits. This method is generally used to shut down the larger programs where all parts of the program are not aware of each other. In such cases, System.exit() is called in order to take care of necessary shutdown tasks like closing file, closing connection, freeing resources etc.

One thing I would like to mention, this method never returns normally i.e the method won't return anything, once a thread goes there, it won't come back.

Also, if you have code which contains the non-daemon threads, you need to use System.exit() to shut down all non-daemon threads and release other resources. If there are no other non-daemon threads, returning from main will automatically shut down the JVM and will call the shutdown hooks.

answered Sep 28, 2018 by code.reaper12
• 3,500 points

Related Questions In Java

0 votes
2 answers

What is the use of toString method in Java and how can I use it ?

Whenever you require to explore the constructor ...READ MORE

answered Aug 23, 2018 in Java by Daisy
• 8,140 points
4,944 views
0 votes
1 answer

Why the main() method in Java is always static?

As you might know, static here is ...READ MORE

answered May 9, 2018 in Java by geek.erkami
• 2,680 points
2,746 views
0 votes
1 answer

How to calculate method execution time in Java ?

Use the following code : new Timer(""){{ ...READ MORE

answered May 25, 2018 in Java by