java.lang
is the package, which isn’t needed with the correct import
statement. System
is a class in the java.lang
package. out
is a static public field (requires no bound instance, like a global variable) in the System
class which has type PrintStream
.
A PrintStream adds functionality to another output stream, namely the
ability to print representations of various data values conveniently.
Two other features are provided as well. Unlike other output streams,
a PrintStream never throws an IOException; instead, exceptional
situations merely set an internal flag that can be tested via the
checkError method. Optionally, a PrintStream can be created so as to
flush automatically; this means that the flush method is automatically
invoked after a byte array is written, one of the println methods is
invoked, or a newline character or byte (‘\n’) is written.
This PrintStream
is connected behind the scenes to an OutputStream
which can either be connected to IDE output or console output (via Java Native Interface).
The arguments to the print
method "string" + i
are concatenated using the +
operator into a big string, which can be directly fed to the print method. i
is a primitive int
type so is temporarily converted in memory to String
during concatenation. As for string concatenation optimisation behind the scenes:
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an
intermediate String object. To increase the performance of repeated
string concatenation, a Java compiler may use the StringBuffer class
(ยง20.13) or a similar technique to reduce the number of intermediate
String objects that are created by evaluation of an expression.For primitive objects, an implementation may also optimize away the creation of a wrapper object by converting directly from a
primitive type to a string.
solved What exactly happens when you print output in Java?