Sub topic 1
Standard input and System.in
Every console program needs a way to receive text from the person running it. In Java that starts with System.in. This chapter explains what System.in is, how bytes typed at a terminal reach your program, and what behaviors of the stream cause problems later when you wrap it in a Scanner or other reader.
Prerequisites
This chapter assumes you can:
- Write and run a small Java program from the command line with
javacandjava, or withjava File.java. - Use
String,int, andchar, and know thatcharandbyteare different types. - Read a
try/catchblock and athrows IOExceptionclause. - Use basic shell features such as pipes (
|) and file redirection (<,>).
You do not need to know Scanner yet. The next chapter introduces it.
What standard input is
Every process started by an operating system gets three standard streams. They exist before your main method runs.
| Stream | Purpose | Java field | Type |
|---|---|---|---|
| Standard input | Data going into the program | `System.in` | `InputStream` |
| Standard output | Normal results | `System.out` | `PrintStream` |
| Standard error | Diagnostics and errors | `System.err` | `PrintStream` |
By default, standard input is connected to the keyboard through the terminal. It does not have to be. The shell can connect it to a file or to the output of another program, and your Java code cannot tell the difference. This is why a program that reads from System.in works both interactively and in scripts.
System.in is a stream of bytes
System.in is declared as InputStream. An InputStream delivers raw bytes and knows nothing about characters, lines, or numbers. Its basic method is read():
- It returns the next byte as an
intin the range 0 to 255. - It returns
-1when there is no more input. - It blocks, meaning the thread waits, until a byte arrives or the stream ends.
It returns int instead of byte so that -1 cannot be confused with a real byte value. A byte in Java is signed, so the value 255 would otherwise look like -1.
This program prints every byte it receives:
import java.io.IOException;
public class RawBytes {
public static void main(String[] args) throws IOException {
int b;
int count = 0;
while ((b = System.in.read()) != -1) {
count++;
System.out.println("byte " + count + " = " + b);
}
System.out.println("Total: " + count);
}
}Compile it and feed it two letters and a newline from a Unix shell:
javac RawBytes.java
printf 'Hi\n' | java RawBytesThe output is:
byte 1 = 72
byte 2 = 105
byte 3 = 10
Total: 3The values 72 and 105 are the ASCII codes for H and i. The value 10 is the line feed character that \n produces. Line terminators are ordinary bytes in the stream, and this is the root of the leftover-newline pitfall covered in a later chapter. On Windows, pressing Enter in a terminal typically sends two bytes, 13 then 10.
From bytes to characters
Text is not bytes. A character encoding such as UTF-8 defines how bytes map to characters, and one character can take several bytes. To get characters from System.in you need a decoder. Java provides InputStreamReader, which takes an InputStream and a Charset and converts bytes to char values.
The next program reads all of standard input as bytes and then decodes it explicitly, so you can see the difference between the two counts:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class BytesVsChars {
public static void main(String[] args) throws IOException {
byte[] data = System.in.readAllBytes();
String text = new String(data, StandardCharsets.UTF_8);
System.out.println("bytes: " + data.length);
System.out.println("chars: " + text.length());
}
}printf 'é' | java BytesVsCharsbytes: 2
chars: 1The letter é is one character but two bytes in UTF-8. If you decode with the wrong charset, you get garbled text such as é. Scanner and BufferedReader both do this decoding for you, so you need to know which charset they use. new Scanner(System.in) uses the JVM default charset. From Java 18 onward that default is UTF-8, but a Windows terminal may still send bytes in a different code page. If accented characters arrive corrupted, pass a Charset explicitly to the Scanner or InputStreamReader constructor.
How input travels to your program
Several layers sit between your keyboard and your code. The diagram shows the path for interactive input.
The terminal's line editor matters most for beginners. In the usual terminal mode (called canonical or cooked mode), the terminal holds what you type until you press Enter. Backspace edits the pending text without your program ever seeing it. Only when you press Enter does the whole line, including the newline, become readable. This has two consequences:
- A call such as
System.in.read()blocks until you press Enter, even if you have typed several characters. - Your program cannot react to a single keypress with plain
System.in. Reading unbuffered key events requires terminal control that standard Java does not provide.
Redirection, pipes, and end of input
Because System.in is just a stream, the shell can connect it to other sources:
java RawBytes < data.txt
printf 'abc' | java RawBytesIn both cases the program reads until the source runs out. At that point read() returns -1. This is called end of input (or end of file, EOF). It is not an error. It is the normal signal that nothing more will arrive.
When you type at the keyboard, you signal end of input yourself:
- On Linux and macOS, press Ctrl+D at the start of a line.
- On Windows, press Ctrl+Z, then Enter.
Later chapters show how Scanner and BufferedReader report end of input in their own ways: hasNext() returns false, readLine() returns null, and nextLine() throws NoSuchElementException. All of them come from this single -1 at the stream level.
Gotchas when sharing System.in
System.in is one global stream for the whole JVM. Keep these points in mind.
Wrappers read ahead
Scanner and BufferedReader keep an internal buffer and fill it by reading a block of bytes at a time, not byte by byte. If you create one wrapper, read a line, and then create a second wrapper on System.in, the first wrapper may already have consumed more input than you used. The second wrapper never sees those bytes. Create one wrapper per program and pass it to the methods that need it, as in the readInt(Scanner in, String prompt) helper style used in later chapters.
Closing the wrapper closes the stream
Calling close() on a Scanner or BufferedReader closes the underlying stream, which here is System.in. After that you cannot read from standard input again in the same JVM. A later chapter covers when this matters. For now, do not create and close a new Scanner inside a method that is called many times.
available() is not a length
System.in.available() returns an estimate of the bytes that can be read without blocking. For a terminal it often returns 0 even when you are about to type something. For a file or pipe it may return a partial amount. Do not use it to detect end of input. Only a -1 from read() means the stream is over.
Standard input can be replaced for testing
System.setIn swaps the global stream. It lets you test input code without typing:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class FakeInput {
public static void main(String[] args) {
InputStream original = System.in;
try {
String fake = "Ada\n";
System.setIn(new ByteArrayInputStream(fake.getBytes(StandardCharsets.UTF_8)));
Scanner in = new Scanner(System.in);
System.out.println("Hello, " + in.nextLine());
} finally {
System.setIn(original);
}
}
}The program prints Hello, Ada without waiting for the keyboard. Restoring the original stream in finally keeps other code in the same JVM unaffected. Note that the Scanner is created after setIn. A Scanner built earlier would still hold the old stream.
Common mistakes
- Treating a byte as a character.
(char) System.in.read()works for ASCII only. For any other text it produces wrong characters, because one character can span several bytes. - Ignoring the
-1. A loop likewhile (true) { int b = System.in.read(); ... }never ends when input is piped from a file, and it keeps processing-1as data. - Expecting a prompt to appear before input is read.
System.out.printwithout a newline may sit in a buffer on some setups. CallSystem.out.flush()if a prompt does not show up before the program waits. - Assuming input is always a person. Code that works at the keyboard may receive an empty stream in a script or a CI job. Always plan for end of input.
Summary
- Standard input is a process-level stream, and
System.inis its Java handle, anInputStreamof bytes. read()returns 0 to 255 for data and-1at end of input, and it blocks while waiting.- Turning bytes into text needs a charset, which
InputStreamReader,Scanner, andBufferedReadersupply. - A terminal normally delivers input only after Enter, and the newline is a real byte in the stream.
System.inis shared and global. Use a single wrapper, and do not close it casually.
Exercise
A program runs printf 'AB\n' | java RawBytes using the RawBytes class from this chapter. List the byte values it prints and the final total, assuming a Unix shell and ASCII text.
Show answer
It prints 65 (A), 66 (B), and 10 (the line feed), so the three lines are "byte 1 = 65", "byte 2 = 66", "byte 3 = 10", followed by "Total: 3". The newline counts as a byte because standard input delivers it like any other byte.
Exercise
Why does System.in.read() return an int instead of a byte, and what does it return when the user presses Ctrl+D (Linux or macOS) at the start of an empty line?
Show answer
A Java byte is signed and ranges from -128 to 127, so it cannot hold both every possible data value (0 to 255) and a separate end-of-input marker. Returning an int lets read() use 0 to 255 for data and -1 for end of input. After Ctrl+D at the start of a line, read() returns -1.
Exercise
You build Scanner a = new Scanner(System.in), read one line with it, and then build Scanner b = new Scanner(System.in) to read the next line. When input is piped from a file, the second scanner sometimes sees nothing. Why, and how do you fix it?
Show answer
The first Scanner reads a block of bytes into its internal buffer, so it can consume more of the stream than the one line you asked for. Those bytes are no longer in System.in, and the second Scanner cannot see them. Fix this by creating a single Scanner and passing it to every method that needs input.