Java Input
Where a Program's Input Comes From
A program becomes useful when it can work with data it didn't have when it was written. Java programs receive input from several sources, and choosing the right one is part of designing a program:
| Source | How Java receives it | Typical use |
|---|---|---|
| Command-line arguments | The String[] args parameter of main | File names, options and flags given when the program starts (java Report sales.csv --month 11) |
| Standard input | System.in | Text typed at the keyboard, or data piped from another program or file (cat data.txt | java Sum) |
| The console | System.console() | Interactive prompts, especially passwords (Console Input lesson) |
| Environment variables | System.getenv(...) | Deployment configuration: ports, database URLs, secrets |
| System properties | System.getProperty(...) | JVM-level settings passed with -Dname=value |
| Files | Files, readers, streams | Configuration files and data (File Handling lessons) |
| Network | Sockets, HTTP clients | Requests and responses (Networking section) |
This lesson covers the first group — the inputs every Java program has available when it starts — and how they're used together in a command-line tool. The Scanner Class and Console Input lessons then go deeper into interactive keyboard input.
Command-Line Arguments
Everything typed after the class name when starting a program is passed to main as an array of strings:
public class Args {
public static void main(String[] args) {
System.out.println("argument count: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "] = \"" + args[i] + "\"");
}
}
}
Running it:
java Args report.csv --verbose "Chennai Central" 42
Output:
argument count: 4
args[0] = "report.csv"
args[1] = "--verbose"
args[2] = "Chennai Central"
args[3] = "42"
How arguments are formed:
- The shell (Bash, PowerShell, Command Prompt) splits the command line at spaces before Java sees it. Quotes keep words together:
"Chennai Central"arrives as one argument, without the quotes. - Every argument is a
String, even42. Convert it yourself withInteger.parseInt(args[3]), and handleNumberFormatExceptionfor invalid input. - With no arguments,
argsis an empty array (args.length == 0), nevernull. Accessingargs[0]without checking the length throwsArrayIndexOutOfBoundsException— a very common crash in small programs. - The arguments of the
javalauncher itself (like-cpor-Dname=value) go before the class name and aren't included inargs.
In an IDE, arguments are set in the run configuration; with the single-file launcher, java Args.java one two passes one and two.
Arguments are best for values known when the program starts and that change from run to run: which file to process, which options to apply. Their weakness is that they're visible to other users on the same machine (for example in ps output on Linux), so never pass passwords or tokens as arguments.
Standard Input: System.in
System.in is an InputStream connected to the program's standard input. What that is depends on how the program was started:
- In a terminal, it's the keyboard. Input becomes available line by line, when the user presses Enter.
- With a pipe (
producer | java Program) or redirection (java Program < data.txt), it's the output of another program or the content of a file. The program can't tell the difference unless it checks — which is exactly what makes command-line tools combinable.
System.in is a byte stream:
import java.io.IOException;
public class Raw {
public static void main(String[] args) throws IOException {
System.out.println("System.in is a " + System.in.getClass().getName());
int b;
int count = 0;
while ((b = System.in.read()) != -1) {
System.out.print(b + " ");
count++;
}
System.out.println("\n" + count + " bytes read");
}
}
Running it with two lines of piped input (printf 'Hi\n₹' | java Raw):
System.in is a java.io.BufferedInputStream
72 105 10 226 130 185
6 bytes read
System.in.read()returns the bytes exactly as received:H(72),i(105), newline (10) and the three UTF-8 bytes of₹.-1means end of input. With a pipe or file, it comes when the data runs out. At an interactive terminal, the user signals it with Ctrl+D (Linux and macOS) or Ctrl+Z then Enter (Windows).read()blocks — it waits until input is available. A program readingSystem.inin a terminal simply pauses until the user types something.
Working with raw bytes is rarely what you want for text. Wrap System.in in a reader that decodes it.
Reading lines from standard input
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Lines {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
int total = 0, count = 0;
String line;
while ((line = in.readLine()) != null) {
line = line.strip();
if (line.isEmpty()) continue;
total += Integer.parseInt(line);
count++;
}
System.out.println(count + " numbers, total " + total);
}
}
Running it with piped input (printf '120\n 80\n\n300\n' | java Lines):
3 numbers, total 500
InputStreamReaderconverts the bytes to characters using UTF-8, andBufferedReaderprovidesreadLine(), which returnsnullat the end of input.strip()removes surrounding spaces and the loop skips blank lines, so slightly messy input still works.- Notice the reader is not closed. Closing it would close
System.in, and nothing in the program could read standard input again. The general rule: don't close streams you didn't open —System.in,System.outandSystem.errbelong to the JVM. - For interactive programs that ask questions and parse numbers and words,
Scanneris more convenient (next lesson).BufferedReaderis faster and better suited to processing large piped input.
Environment Variables and System Properties
Configuration that depends on where the program runs — which port to use, which database to connect to — usually comes from the environment rather than from arguments.
public class Env {
public static void main(String[] args) {
String port = System.getenv().getOrDefault("APP_PORT", "8080");
String profile = System.getProperty("app.profile", "dev");
System.out.println("APP_PORT env var: " + port);
System.out.println("app.profile property: " + profile);
System.out.println("java.version: " + System.getProperty("java.version").split("\\.")[0]);
System.out.println("HOME is set: " + (System.getenv("HOME") != null));
}
}
Running it on Linux with both values set (APP_PORT=9090 java -Dapp.profile=prod Env):
APP_PORT env var: 9090
app.profile property: prod
java.version: 21
HOME is set: true
And without them (java Env):
APP_PORT env var: 8080
app.profile property: dev
java.version: 21
HOME is set: true
| Environment variables | System properties | |
|---|---|---|
| Set by | The operating system, shell, container or service manager (export APP_PORT=9090, Docker -e, Kubernetes) | The java command (-Dapp.profile=prod) or System.setProperty |
| Read with | System.getenv("NAME"), System.getenv() (a Map) | System.getProperty("name"), System.getProperty("name", default) |
| Scope | Inherited by child processes | Only this JVM |
| Can the program change them? | No (read-only in Java) | Yes |
| Built-in values | PATH, HOME/USERPROFILE, ... | java.version, user.dir, user.home, os.name, line.separator, java.io.tmpdir, ... |
System.getenv("NAME")returnsnullwhen the variable isn't set;System.getenv().getOrDefault(...)and the two-argumentgetPropertysupply defaults.- Environment variable names are case-sensitive on Linux and macOS but not on Windows.
- Environment variables are the standard way to configure containerised applications (the "Twelve-Factor App" approach), and frameworks such as Spring Boot read them automatically (
SERVER_PORT→server.port). They're also the usual way to provide secrets, which shouldn't appear in arguments or in source code.
Practical Example: A Command-Line Word Counter
Real command-line tools combine these input sources: options and a file name from arguments, data from a file or from standard input, and errors reported with an exit code. This simplified version of the Unix wc command shows the conventions.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class Wc {
record Counts(long lines, long words, long chars) { }
static Counts count(BufferedReader in) throws IOException {
long lines = 0, words = 0, chars = 0;
String line;
while ((line = in.readLine()) != null) {
lines++;
chars += line.length();
String trimmed = line.strip();
if (!trimmed.isEmpty()) words += trimmed.split("\\s+").length;
}
return new Counts(lines, words, chars);
}
public static void main(String[] args) {
boolean wordsOnly = false;
String fileName = null;
for (String a : args) {
switch (a) {
case "-w", "--words" -> wordsOnly = true;
case "-h", "--help" -> {
System.out.println("usage: java Wc [-w] [FILE] (reads standard input when FILE is omitted)");
return;
}
default -> {
if (a.startsWith("-")) {
System.err.println("unknown option: " + a);
System.exit(2);
}
fileName = a;
}
}
}
try (BufferedReader in = fileName == null
? new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))
: Files.newBufferedReader(Path.of(fileName))) {
Counts c = count(in);
String source = fileName == null ? "(stdin)" : fileName;
System.out.println(wordsOnly ? c.words() + " " + source
: c.lines() + " lines, " + c.words() + " words, " + c.chars() + " chars " + source);
} catch (NoSuchFileException e) {
System.err.println("wc: " + e.getFile() + ": no such file");
System.exit(1);
} catch (IOException e) {
System.err.println("wc: " + e.getMessage());
System.exit(1);
}
}
}
With notes.txt containing two lines (Java input can come from many places. and Files, pipes and the keyboard.), four runs produce:
$ java Wc notes.txt
2 lines, 12 words, 67 chars notes.txt
$ printf 'one two\nthree\n' | java Wc -w
3 (stdin)
$ java Wc nope.txt
wc: nope.txt: no such file (exit code 1)
$ java Wc -x
unknown option: -x (exit code 2)
How it works:
- Parsing arguments. The loop examines each argument. A
switchwith multiple labels (case "-w", "--words") accepts short and long option forms. Anything else starting with-is an unknown option; any other argument is the file name. Options can therefore appear in any order. Larger tools use a library such as picocli for this, but the principle is the same. - Choosing the input source. If a file name was given, the tool reads that file; otherwise it reads standard input. Both are wrapped as a
BufferedReader, socountdoesn't know or care where the text comes from. This is what lets the tool work in a pipeline. - Closing in try-with-resources. Closing the reader is correct for the file. For standard input it also closes
System.in, which is acceptable here only because the program ends right afterwards; a program that continued would have to avoid closing it. - Counting. Lines are counted per
readLine(), characters per line (without line terminators), and words by splitting the stripped line on runs of whitespace (