Insights into Company
← Java

Input and Output

01 Input and Output in Java

Solution and explanation

What it is

Input is data a program reads (keyboard, file, network); output is data it writes (console, file, socket). Java models both as streams: a sequence of bytes or characters flowing in one direction.

  • Byte streams (InputStream, OutputStream) handle raw bytes: images, PDFs, network data.
  • Character streams (Reader, Writer) handle text and take care of character encoding (UTF-8).
  • System.in is the keyboard input stream, System.out the console output stream, System.err the error stream.

Reading from the keyboard with Scanner

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();          // whole line
        System.out.print("Enter your age: ");
        int age = sc.nextInt();               // next integer token
        System.out.printf("Hello %s, next year you will be %d%n", name, age + 1);
        sc.close();
    }
}

Note: after nextInt() the newline is still in the buffer, so a following nextLine() returns an empty string. Call sc.nextLine() once to consume it.

Fast input for competitive programming

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken());

BufferedReader reads large chunks at once and is many times faster than Scanner for big inputs.

Output

System.out.println("Total: " + 42);          // prints and adds a newline
System.out.print("No newline");
System.out.printf("%-10s|%8.2f%n", "Laptop", 54999.5);   // formatted: left-aligned text, 2 decimals

Reading and writing files (java.nio)

Path path = Path.of("jobs.txt");
Files.writeString(path, "Java Developer\nSpring Boot Engineer\n");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);

try (BufferedWriter w = Files.newBufferedWriter(Path.of("out.csv"))) {
    w.write("id,title");
    w.newLine();
}

Summary

  • Scanner: easy keyboard input; BufferedReader: fast input.
  • println/printf for output; %d integer, %s string, %.2f decimal, %n newline.
  • Use Files and try-with-resources for files so streams are always closed.

Display console output

System.out.print() remains on the same line. System.out.println() prints and then starts a new line.

Read user input

Import java.util.Scanner, connect it to System.in, then use the method matching the value type.

Common Scanner methods

nextInt(): integer · nextLong(): long · nextDouble(): decimal · next(): word · nextLine(): line · next().charAt(0): character.

Important input rule

After nextInt() or nextDouble(), consume the remaining newline before nextLine(), or it may appear to be skipped.

Interactive I/O code lab
Output
Select Run to test the supplied input.

This guided browser lab validates this lesson's input/output flow without executing untrusted code on the Laravel server.

Run this example
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        int age = scanner.nextInt();
        double height = scanner.nextDouble();
        char grade = scanner.next().charAt(0);
        System.out.println("----- Student Details -----");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height);
        System.out.println("Grade: " + grade);
        scanner.close();
    }
}
Hands-on challenge

Ask for a full name, city, age and favourite programming language, then print a formatted profile summary.

Quick check

Which statement is correct?