Java Input/Output  «Prev   Next»

Lesson 3Reading from the standard input
ObjectiveUse the class variable and describe an approach to reading user input.

Java Read Input

When we wrote to the standard output, we used a variable that was tied to the standard output (which is, by default, the screen). This variable was the class variable System.out.
Similarly, when we want to read from the standard input (which is, by default, the keyboard), we use a variable tied to the standard input. This variable is the class variable refers to a variable that is a subclass of Java's InputStream class. This means we can use the methods defined by the InputStream class (in particular, the read() method) to read characters as the user types.
StringBuffer: If you are not familiar with the StringBuffer class, it's a class that keeps track of character data. However, unlike the String class, which is read-only (that is, once you create a String object you cannot change the characters it contains), StringBuffer is read/write. That means we can append the characters we read to the end of a StringBuffer object as we read them from the keyboard.

Here is an example of a program that reads one character at a time from the standard input. It adds each character read, one at a time, to an instance of class StringBuffer and displays the characters read at the end.

Read Standard Input - Exercise

Exercises on reading from the standard input span two lessons.
In this first exercise, you will write a a stand-alone, character-mode program that reads from the standard input into a StringBuffer object.
In the second exercise you will learn about data streams and will add them to the program you write in this exercise.

Read Standard Input - Exercise