Whenever we write any statement to print to console in Java program:
System.out.print
or System.out.println
In above both statements we're calling out reference variable of PrintStream object without explicitly importing java.io package, so how we're accessing that object methods without resulting any compile time error?
out. println is an IO-operation and therefor is time consuming. The Problem with using it in your code is, that your program will wait until the println has finished.
In Java, System. out. println() is a statement which prints the argument passed to it. The println() method display results on the monitor.
To get System. out. println() line in eclipse without typing the whole line type sysout and press Ctrl + space.
System: It is a final class defined in the java. lang package. out: This is an instance of PrintStream type, which is a public and static member field of the System class. println(): As all instances of PrintStream class have a public method println(), hence we can invoke the same on out as well.
The System object has references to java.io.PrintStream
objects embedded in it. So you don't need to explicitly import these - the runtime can derive this information unambiguously since it was embedded at compile-time.
As you've identified, if you used a PrintStream
object directly, you'd have to import that. The compilation stage doesn't know where to find it (it could search, but that could easily give ambiguous results).
Note also (in case there's any confusion), java.lang
is implicitly imported, hence you don't require an import statement for System
.
You only need to import class names for those that you wish to declare. So, for example:
PrintStream out = System.out;
would not compile unless you imported java.io.PrintStream
, but you can use the methods off of System.out, since it is "implicitly" imported at that point, since the compiler knows exactly what type System.out
is. In some languages, for example, Scala, you would not need to declare the type of the variable either, since it can be worked out via type inference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With