Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


The Standard Input Stream

class Count {
    public static void main(String args[])
        throws java.io.IOException
    {
        int count = 0;

        while (System.in.read() != -1)
            count++;
        System.out.println("Input has " + count + " chars.");
    }
}    
System is a member of the java.lang package and provides system functionality such as standard input and output, copying arrays, getting the current date and time, and getting environment variables. The while loop uses the System class to read characters.

All of the System class's methods and variables are class methods and variables. For more information about how to use class methods and variables refer to Static vs. Instance in The Anatomy of a Java Application.

The Standard Input Stream

System.in implements the standard input stream. The standard input stream is a C library concept that has been assimilated into the Java language. Simply put, a stream is a flowing buffer of characters; the standard input stream is a stream that reads characters from the keyboard. The standard input stream is a convenient place for an old-fashioned text-based application to get input from the user.

Reading from the Standard Input Stream

The read() method provided by System.in reads a single character and returns either the character that was read or, if there are no more characters to be read, -1.

When a program reads from the standard input stream, the program blocks waiting for you to type something in. The program continues to wait for input until you give it some indication that the input is complete. To indicate to any program that reads from the standard input stream that you have finished entering characters, type the end-of-input character appropriate for your system at the beginning of a new line. When the character-counting program receives an end-of-input character the loop terminates and the program displays the number of characters you typed.

See Also

java.lang.System


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language