Java Write to Console Output

Console output is most easily accomplished with print() and println() methods, as described earlier. These methods are defined by the class PrintStream which is the type of object referenced by System.in. Even though System.out is a byte stream, using it for a simple program output is still acceptable.

Because the PrintStream is an output stream derived from the OutputStream, it also implements the low-level method write(). Thus, write() can be used to write to the console. The simplest form of write() defined by the PrintStream is shown below :

void write(int byteval)

This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Following is a short example that uses write() to output the character 'X' followed by a newline to the screen:

/* Java Program Example - Java Write Console Output
 * This program writes the character X followed by newline 
 * This program demonstrates System.out.write()  */
 
 class WriteConsoleOutput
 {
     public static void main(String args[])
     {
         
         int y;
         
         y = 'X';
         
         System.out.write(y);
         System.out.write('\n');
         
     }
 }

This Java program will produce the following output:

java write console output

You will not often use write() to perform console output (although doing so might be useful in some situations) because print() and println() are substantially easier to use.

Examples on Files in Java

Here are some examples related to files in Java, you can go for.

Java Online Test


« Previous Tutorial Next Tutorial »