Ankush Dutt
Ankush Dutt

Reputation: 133

what is the purpose of using System.out.println()

I was going through the internal implementation of System.out.println().Though I understood how this is working but couldn't figure out :

  1. Why they decided to use the System class in the first place.
  2. They could have directly used PrintStream class which is present in the io package.

  3. What is the significance of the syntax className.referenceVariable.Methodname, since we generally don't use this. Is there any specific reason for this.

Can anybody elaborate on these points or any related information would be great.

Upvotes: 7

Views: 363

Answers (2)

pri
pri

Reputation: 1531

The System class states that:

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since you were checking the source code of System class, you might've noticed that out object is final and is set to null. It's the setOut() method which assigns a value to the out variable (it's a native code).

I know, how can JVM set value to a final variable after it's been set to null, right? Being a JVM has its own advantages!

Before a value gets assigned to out object, a separate method called checkIO is also triggered, which checks for IO permission.

So System class was designed as a collection of standard input, output, and error streams. It also instructs JVM to initialise the objects, like the out object.

Regarding the syntax of System.out.println(), Eran has already explained it.

Upvotes: 1

Ganesh chaitanya
Ganesh chaitanya

Reputation: 658

According to my understanding, System class name was to indicate any interactions with System on which JVM is running. To perform Read or Write operations on the System Console, or reading environment variables in the System etc.

You can always use PrintStream directly as well there is no harm. But then you have to create a PrintStream object every time in your class and call methods inside use it. Instead its already created statically in System class for us to use it readily.

As for your 3rd query, Eran already answered it in the comments.

Upvotes: 1

Related Questions