Java System setIn() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 1+

Definition

In Java, System.setIn(stream) replaces the standard input stream. After the call, System.in is the InputStream you passed, so code that reads "the keyboard", for example with a Scanner, reads your prepared data instead.

The usual partner is a ByteArrayInputStream built from a string such as "42\n", which lets you test programs that ask questions without anyone typing.

A static method of the java.lang.System class, added in Java 1 (JDK 1.1). Call it on the class name, as in System.setIn(...). No import is needed, because classes in java.lang are always visible.

Syntax

Turn text into bytes, install it as input, and restore the original afterwards:

Java
InputStream original = System.in;
System.setIn(new ByteArrayInputStream("42\n".getBytes(StandardCharsets.UTF_8)));
try {
    Scanner scanner = new Scanner(System.in);  // create it AFTER setIn
    int n = scanner.nextInt();                 // 42
} finally {
    System.setIn(original);
}
CallWhat it does
System.setIn(new ByteArrayInputStream(bytes))Input comes from a byte array in memory.
System.setIn(new FileInputStream("answers.txt"))Input comes from a file.
System.setIn(original)Back to the keyboard (or whatever the program started with).

Added in Java 1.1. A Scanner or BufferedReader created before setIn still holds the old stream, so create readers after redirecting.

Library declarations
Java
// java.lang.System
public static void setIn(InputStream in)

Parameters

ParameterDescription
inThe new standard input stream, for example a ByteArrayInputStream or FileInputStream.

Return Value

Return ValueDescription
voidNothing; System.in refers to in afterwards.

Compare with Similar Methods

Other ways to get input into a program:

MethodHow it differs
setOut(stream)The output side: captures what the program prints.
console()Reads from the real terminal; not affected by setIn.
new Scanner("42")Reads a string directly, if you can change the reading code.
java App < input.txtShell redirect: the file becomes System.in without code changes.

Java Examples

Example 1 — Give a Scanner Prepared Input

Replace the keyboard with the bytes of "42\n" and read them with an ordinary Scanner.

Java
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SystemSetInScanner {
    public static void main(String[] args) {
        InputStream original = System.in;
        System.setIn(new ByteArrayInputStream("42\n".getBytes(StandardCharsets.UTF_8)));
        try {
            Scanner scanner = new Scanner(System.in);
            int number = scanner.nextInt();
            System.out.println("Read: " + number);
            System.out.println("Doubled: " + number * 2);
        } finally {
            System.setIn(original);
        }
    }
}

How It Works

  1. Text becomes a stream. getBytes(StandardCharsets.UTF_8) turns "42\n" into three bytes, and ByteArrayInputStream serves them like keystrokes: '4', '2', then Enter.
  2. Order matters. The Scanner is created after setIn, so it wraps the prepared stream. nextInt() returns 42 at once, without waiting for anyone to type.
  3. Normal input again. The program prints 42 and 84, then finally puts the original System.in back so any later reading uses the real keyboard.

Example 2 — Read Several Lines with BufferedReader

One string with three line breaks acts like a user entering three names. The loop stops at the end of the data, just as it would at Ctrl+D or Ctrl+Z.

Java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class SystemSetInLines {
    public static void main(String[] args) throws IOException {
        String fakeInput = "Ana\nBen\nCara\n";
        InputStream original = System.in;
        System.setIn(new ByteArrayInputStream(fakeInput.getBytes(StandardCharsets.UTF_8)));
        int count = 0;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
            String name;
            while ((name = reader.readLine()) != null) {
                count++;
                System.out.println("Hello, " + name);
            }
        } finally {
            System.setIn(original);
        }
        System.out.println("Names read: " + count);
    }
}

How It Works

  1. Three lines of fake typing. fakeInput holds three names, each ended by "\n". After setIn, those bytes are everything System.in will ever deliver.
  2. Decoding with a known charset. InputStreamReader is given UTF-8 explicitly, matching the getBytes call, so the bytes turn back into exactly the same text on every computer.
  3. End of input ends the loop. readLine() returns each name without its line break, then null once the array is used up. Three greetings are printed and the counter reaches 3.

Example 3 — Test a Yes/No Question with Two Answers

A method asks the user a question. A helper installs a different prepared answer for each call, so both branches can be checked automatically.

Java
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SystemSetInAnswer {
    static boolean askYesNo() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Continue? (y/n) ");
        String answer = scanner.nextLine().trim();
        System.out.println(answer);
        return answer.equalsIgnoreCase("y");
    }

    static boolean answerWith(String typed) {
        InputStream original = System.in;
        System.setIn(new ByteArrayInputStream(typed.getBytes(StandardCharsets.UTF_8)));
        try {
            return askYesNo();
        } finally {
            System.setIn(original);
        }
    }

    public static void main(String[] args) {
        boolean first = answerWith("y\n");
        System.out.println("Result: " + first);
        boolean second = answerWith("N\n");
        System.out.println("Result: " + second);
    }
}

How It Works

  1. Echoing the answer. Prepared input is not shown on screen the way typing is, so askYesNo prints the answer after the prompt; the output then reads like a real session.
  2. Fresh input per call. answerWith installs a new stream for each call, and askYesNo makes a new Scanner each time, so the second question reads "N" and not something left over from the first.
  3. Both branches covered. "y" matches equalsIgnoreCase("y") and returns true; "N" does not, so the second result is false. The finally in the helper restores the keyboard after each call.

Frequently Asked Questions

Call System.setIn(new ByteArrayInputStream("text\n".getBytes(StandardCharsets.UTF_8))) before creating the Scanner, then restore the original System.in afterwards.
The Scanner was probably created before setIn. A Scanner keeps the stream it was given, so create it after redirecting System.in.
Save it first with InputStream original = System.in; and call System.setIn(original) in a finally block.
No. System.console() talks to the real terminal, not to System.in, so prepared input from setIn is not seen by Console.readLine.
Both make System.in read prepared data. The shell redirect needs no code change; setIn works inside the program, for example in a test.

Next: setOut()

Redirect standard output System.out, for example to capture printed text.

setOut() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful