Java Input

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 149 of 306

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:

SourceHow Java receives itTypical use
Command-line argumentsThe String[] args parameter of mainFile names, options and flags given when the program starts (java Report sales.csv --month 11)
Standard inputSystem.inText typed at the keyboard, or data piped from another program or file (cat data.txt | java Sum)
The consoleSystem.console()Interactive prompts, especially passwords (Console Input lesson)
Environment variablesSystem.getenv(...)Deployment configuration: ports, database URLs, secrets
System propertiesSystem.getProperty(...)JVM-level settings passed with -Dname=value
FilesFiles, readers, streamsConfiguration files and data (File Handling lessons)
NetworkSockets, HTTP clientsRequests 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, even 42. Convert it yourself with Integer.parseInt(args[3]), and handle NumberFormatException for invalid input.
  • With no arguments, args is an empty array (args.length == 0), never null. Accessing args[0] without checking the length throws ArrayIndexOutOfBoundsException — a very common crash in small programs.
  • The arguments of the java launcher itself (like -cp or -Dname=value) go before the class name and aren't included in args.

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 ₹.
  • -1 means 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 reading System.in in 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
  • InputStreamReader converts the bytes to characters using UTF-8, and BufferedReader provides readLine(), which returns null at 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.out and System.err belong to the JVM.
  • For interactive programs that ask questions and parse numbers and words, Scanner is more convenient (next lesson). BufferedReader is 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 variablesSystem properties
Set byThe operating system, shell, container or service manager (export APP_PORT=9090, Docker -e, Kubernetes)The java command (-Dapp.profile=prod) or System.setProperty
Read withSystem.getenv("NAME"), System.getenv() (a Map)System.getProperty("name"), System.getProperty("name", default)
ScopeInherited by child processesOnly this JVM
Can the program change them?No (read-only in Java)Yes
Built-in valuesPATH, HOME/USERPROFILE, ...java.version, user.dir, user.home, os.name, line.separator, java.io.tmpdir, ...
  • System.getenv("NAME") returns null when the variable isn't set; System.getenv().getOrDefault(...) and the two-argument getProperty supply 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:

  1. Parsing arguments. The loop examines each argument. A switch with 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.
  2. 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, so count doesn't know or care where the text comes from. This is what lets the tool work in a pipeline.
  3. 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.
  4. Counting. Lines are counted per readLine(), characters per line (without line terminators), and words by splitting the stripped line on runs of whitespace (0s+). An empty line contributes no words.
  5. Output and errors go to different streams. Results go to System.out; error messages go to System.err, so that when the output is redirected into a file (java Wc data.txt > counts.txt), error messages still appear on the screen instead of being mixed into the results.
  6. Exit codes. System.exit(1) signals a runtime failure and System.exit(2) a usage error, following Unix conventions; a normal return from main ends with code 0. Scripts and CI pipelines check the exit code ($? in Bash) to decide whether a step succeeded, so a tool that prints an error but exits with 0 can make a failing pipeline look successful.

System.exit ends the JVM immediately, without unwinding the call stack — finally blocks don't run. That's acceptable in main of a small tool after everything is done, but in libraries and servers you should throw exceptions instead and let the top level decide.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Input and get answers drawn from it.

Signed-in readers only.