Java Console Input and Output Methods

Java Console Input and Output Methods

Reading Strings from Console

To read a string from standard input in Java, you can use the readLine() method of BufferedReader.

The general syntax is:

String readLine() throws IOException

The following program demonstrates reading and displaying lines of text until the user enters the word "exit":

// Using BufferedReader to read from console
import java.io.*;

public class ConsoleInputExample {
    public static void main(String args[]) throws IOException {
        // Create BufferedReader using System.in
        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
        String inputText;
        
        System.out.println("Enter text lines.");
        System.out.println("Type 'exit' to finish.");
        
        do {
            inputText = consoleReader.readLine();
            System.out.println("You entered: " + inputText);
        } while (!inputText.equals("exit"));
    }
}

Sample output when cmopiling and running this program:

Enter text lines.
Type 'exit' to finish.
Hello world
You entered: Hello world
This is a test
You entered: This is a test
exit
You entered: exit

Note: For Java versions 5 and later, you can also use the Java Scanner class to get console input.

Console Output

As previously mentioned, console output is handled by the print() and println() methods. These methods are defined by the PrintStream class, and System.out is a reference to an object of this class.

PrintStream inherits from the OutputStream class and implements the write() method. This allows you to use write() for console output as well.

The simplest format of write() as defined by PrintStream is:

void write(int byteval)

This method writes the lower eight bits of byteval to the stream.

Example

The following example uses write() to output the character "X" followed by a newline to the screen:

import java.io.*;

// Demonstrating System.out.write()
public class ConsoleOutputExample {
    public static void main(String args[]) {
        char characterValue;
        characterValue = 'X';
        System.out.write(characterValue);
        System.out.write('\n');
    }
}

Runing this example outputs "X" character in the console:

X

Note: The write() method is not commonly used since print() and println() methods are more convenient for most output scenarios.

Tags: java console-io BufferedReader Scanner printstream

Posted on Fri, 31 Jul 2026 16:48:49 +0000 by starmsa