File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes java.lang.System vs java.lang.Runtime Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java.lang.System vs java.lang.Runtime " Watch "java.lang.System vs java.lang.Runtime " New topic

java.lang.System vs java.lang.Runtime

Abhineet Kapil
Ranch Hand

Joined: Feb 08, 2010
Posts: 52


1.Whats the difference between System.gc() and Runtime.gc().
2.Whats the difference between System.exit(0) and Runtime.halt(1).

Please put some light on it.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20276

Please read the Javadoc of java.lang.System and java.lang.Runtime and all will be revealed.

How To Ask Questions How To Answer Questions
Jose Monzon

Joined: Jun 05, 2008
Posts: 8
Oh, that's an easy one. As our friend says, the documentation says it all.

Basically System.exit() calls to Runtime.getRuntime().exit(). (yes, because Runtime.exit() is a compile exception. that method is NOT static. The only static method there getInstance() and another one I don't even going to bother to remember because it's deprecated)

Question is, why are there two ways to perform the same functionality? Well, by convention, historical reasons and convenience.

A closer look to the Runtime class tells us that it follows the 'Factory method' pattern. This is, its constructor is private (to prevent you from creating new instances of Runtime) and there is an static reference that you access through Runtime.getRuntime() -the pattern says the method should be called: getInstance() , but anyways... -. The 'Factory method' pattern is a great solution for singleton objects, like in this case. I know you didn't asked this, but nevertheless ;-)

Here, I found an implementation of Runtime:

Funny to see that Runtime.exit() calls to yet another static method Shutdown.exit(). But that's a package-private class you don't even have to worry about.

I agree. Here's the link:
subject: java.lang.System vs java.lang.Runtime
It's not a secret anymore!