Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in System.out.println statement

Tags:

java

import

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?

like image 636
Stardust Avatar asked Jan 23 '10 13:01

Stardust


People also ask

Why system out Println should not be used?

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.

Is system out Println a statement?

In Java, System. out. println() is a statement which prints the argument passed to it. The println() method display results on the monitor.

How do I make system out Println faster?

To get System. out. println() line in eclipse without typing the whole line type sysout and press Ctrl + space.

What is the use of system out Println (); in Java programming give an example?

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.


2 Answers

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.

like image 167
Brian Agnew Avatar answered Oct 29 '22 04:10

Brian Agnew


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.

like image 30
Paul Wagland Avatar answered Oct 29 '22 03:10

Paul Wagland