PrintStream out = System.out;
out.println( "hello" );
You will have to create an object out first. More about this here:
// write to stdout
out = System.out;
out.println("Test 1");
out.close();
Well, you would typically use
System.out.println("print something");
which doesn't require any imports. However, since out is a static field inside of System, you could write use a static import like this:
import static java.lang.System.*;
class Test {
public static void main(String[] args) {
out.println("print something");
}
}
Take a look at this link. Typically you would only do this if you are using a lot of static methods from a particular class, like I use it all the time for junit asserts, and easymock.
out
is a PrintStream
type of static variable(object) of System
class and println()
is function of the PrintStream
class.
class PrintStream
{
public void println(){} //member function
...
}
class System
{
public static final PrintStream out; //data member
...
}
That is why the static variable(object) out
is accessed with the class name System
which further invokes the method println()
of it's type PrintStream
(which is a class).
you can see this also in sockets ...
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("hello");
simply import :
import static java.lang.System.*;
Or simply:
System.out.println("Some text");
@sfussenegger's answer explains how to make this work. But I'd say don't do it!
Experienced Java programmers use, and expect to see
System.out.println(...);
and not
out.println(...);
A static import of System.out or System.err is (IMO) bad style because:
If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.
Source: Stackoverflow.com