1

Firstly sorry if this a very basic question but someone ask me this and i don't have any answer.

In the statement

    System.out.println()

System is a class in java.lang package, out is a static variable of System class and println() is an overloaded method. Then Why System class doesn’t requires instantiation?

Thanks

john
  • 21
  • 2
  • okay you mean system is a static class which doesn't need instantiation? – john Jul 08 '20 at 06:39
  • 2
    No; read your own description again. `out` is a static *field* (variable, as you put it), of System. System is special; it's not `static`, but it can't be instantiated. But we don't need to instantiate it, because it stores a `PrintStream` named `out` in *the class itself*, not in instances. – Karl Knechtel Jul 08 '20 at 06:43
  • 3
    If you look at Integer, it has static and non-static methods. You need an instance when you call non-static methods. non-static. `Integer i = 1`; then `i.toString()` versus the static version. `Integer.toString(1)` where you don't need an instance. – matt Jul 08 '20 at 06:44
  • 3
    Does this answer your question? [out in System.out.println()](https://stackoverflow.com/questions/9454866/out-in-system-out-println) – Timothy Jul 22 '21 at 14:56

3 Answers3

1

java.lang.* is imported by default, i.e. all classes in the java.lang.* package are accessible by your program. So, your class has access to the members of the System class, among which is out, a static field of type PrintStream. Static members are not tied to an instance of the class, and so they can be accessed directly without instantiation. Hence, you are able to call the overloaded print methods available to out.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Tom
  • 355
  • 4
  • 11
0

If you declare a static method in a Java class you don't need to create an object but simply invoke the method like System.out.println().

Marc
  • 2,738
  • 1
  • 17
  • 21
0

The System class cannot be instantiated anyway (cf. Javadoc).

This is achieved by setting the constructor to private:

private System() {
}

However, the System class in openj9 for example is partially filled by call of the afterClinitInitialization() method, which is called after thread initialization.

In there, the out Variable is actually initialized:

setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true));

See:

System.afterClinitInitialization()

Thread.initialize()

After that it stops being traceable via Github, but I guess you get the point. The initialization is just done by the JVM and due to out being static, no instance of System is needed to access the variable.

The topic of static variables however is well covered:

What does the 'static' keyword do in a class?

Static (Keyword) - Wikipedia.com

And to fully understand that, you must have a decent knowledge of the JVM and native programming, where I have to surrender myself.

maio290
  • 6,440
  • 1
  • 21
  • 38