Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Basics Perfecting the Prototype Reviewing Our Feedback

Not understanding System.exit(0).

In Craig's Intro to Java class he sets up a conditional statement for age restriction, but within that conditional statement he also includes system.exit with a value of 0. I'm not understanding:

1) Why do we need to have a special exit program code within a conditional? Wouldn't the conditional either be met or not and exit on its own?

2) When do we use this system.exit(0)?

3) Why do we use system.exit(0) at all? It seems similar to ejecting a flash drive in terms of a safer(?) way to exit a program than just abruptly exiting...but I'm not clear on that... 3A) If it is "safer" to use the system.exit(0) in some situations, how do we determine
the "safety" level of a particular part of a program?

4) Aren't we forcing the program to an artificial safe exit using system.exit(0) vs. letting it exit naturally?

5) What does 0 stand for or mean? Craig says it means that we exited normally, but in what... the compiler?

2 Answers

  1. System.exit() ends the program. The code directly following the "System.exit()" call does not execute. Yes, If Statements terminate after the closing bracket, but what Craig wanted to do was end the program.

  2. You use it to terminate the JVM.

  3. You seem to think that the program would have ended just the same if the "System.exit()" call was not made. Based on the video, there was code after the if statement.

  4. Yes.

  5. The "0" parameter is default. You don't need it (I think). Anything other than "0" indicates that the execution did not go well. You see the numbers in the console. It's meant for error-finding.

As Billy said, the System.exit() stops the program running, without it the 'if' statement does return a value but the program will still run the rest of the code.