I noticed that any call to System.out.println()
from a JAR file that hasn\'t been started by the command line (i.e. a Runnable JAR file started by user with dou
System
is final
class from java.lang
package(default package in java) and cannot be instantiated.
out
is a static
member field of System
class and is of type PrintStream
and its access specifiers are public final
.
println
– is an overloaded method of PrintStream
class. println
prints the argument passed to the standard console and a newline. There are multiple println
overloaded methods with different arguments. Every println
makes a call to print method and adds a newline. Internally, print calls write()
and write()
takes care of displaying data to the standard output window.
Here it is how it should look in the inside:
//the System class belongs to java.lang package
class System {
public static final PrintStream out;
//...
}
//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}
We therefore don't need to ever instantiate a System
object to print messages to the screen; we simply call the println
method on the System class's public static PrintStream
member, out
.
But you cannot create an object of PrintStream
and call the println
function. When you want to print to the standard output, then you will use System.out
. That's the only way. Instantiating a PrintStream
will allow you to write to a File or OutputStream you specify, but don't have anything to do with the console.
However, you can pass System.out
to PrintStream
and then invoke println on PrintStream
object to print to the standard output. Here is a small example:
import java.io.*;
public class SystemOutPrintlnDemo
{
public static void main(String[] args)
{
//creating PrintStream object
PrintStream ps = new PrintStream(System.out);
ps.println("Hello World!");
ps.print("Hello World Again!");
//Flushes the stream
ps.flush();
}
}