Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Bear in mind that Java code runs in the JVM, and the JVM only communicates to the outside world in a few specified ways. So if you want to print to a console, you will need to call a method that somehow (after JNI, etc.) gets mapped to an IO operation on your actual OS. Unless you plan on building a new OS-level IO operation (in which case you can't write it in Java anyway), your best bet is to use an existing class that already knows how to talk to the outside world.</p> <p>As it happens, the <code>java.io.PrintStream</code> class knows how to write to an OS level file stream, and the OS provides a file stream for the console (<code>stdout</code>). (Technically, <code>PrintStream</code> only knows how to write to an <code>OutputStream</code>, and <code>OutputStream</code> knows how to write to an OS level file stream, but I don't want to get bogged down in details.) Java provides an instance of <code>PrintStream</code> already attached to your process's standard output stream; that <code>PrintStream</code> object can be referenced as the <code>out</code> property of the <code>java.lang.System</code> object. Given that <code>PrintStream</code> has methods like <code>println()</code>, you can write:</p> <pre><code>java.lang.System.out.println("Hello, world!"); </code></pre> <p>Since you always get <code>java.lang.*</code> imported by default, you can shorten that to:</p> <pre><code>System.out.println("Hello, world!"); </code></pre> <p>Alternatively, you can assign the <code>PrintStream</code> instance to a local variable:</p> <pre><code>import java.io.PrintStream; public class HelloWorld { public static void main(String[] args) { PrintStream p = System.out; p.println("Hello, world!"); } } </code></pre> <p>What does your "user defined method to print" do that the <code>println()</code> method of <code>PrintStream</code> objects doesn't? If you're interested in <strong>formatting</strong> the output, then you need to format it as a <code>String</code> <strong>before</strong> you call the <code>println()</code> method. As a convenience, you can wrap up the formatting and actual printing in a single helper method. Is this what you're actually looking for?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload