› Module 3: Input and Output › 3.3 BufferedReader for Faster Input
M O D U L E

Module 3: Input and Output

Console output with System.out, beginner-friendly input parsing using Scanner, and high-performance BufferedReader.

3.1 System.out: print, println, printf

Before a program can interact meaningfully with users, it must communicate through standard input and output streams. In Java, console output is managed through System.out, which represents a standard output byte stream wrapped in a java.io.PrintStream instance.

The Three Output Methods

  • print(): Writes text to the console without terminating the line. The cursor remains on the same line, allowing subsequent outputs to append immediately adjacent to it.
  • println(): Writes text and automatically terminates the current line with an OS-dependent line separator ( on Linux/macOS, on Windows). This is the standard choice for structured terminal logging.
  • printf(): Borrowed from C, this method produces formatted strings using formatting placeholders and argument lists:
    String name = "Alice";
    int score = 95;
    double gpa = 3.876;
    System.out.printf("%s scored %d points with GPA: %.2f%n", name, score, gpa);

💡 Placement & Interview Deep-Dive

  • What exactly is System.out.println() under the hood? System is a final utility class in java.lang. out is a public static final PrintStream field belonging to the System class that is initialized by the JVM at startup to point to standard output. println() is an overloaded instance method in PrintStream.
  • Why use %n instead of \n inside printf? produces only a line-feed, which may not render correctly on certain Windows terminals expecting CRLF. %n is Java's platform-independent format specifier that emits the exact newline sequence of the current host operating system.

3.2 Reading Input with Scanner

The Scanner class (residing in java.util) is the standard, beginner-friendly tool for parsing keyboard input. It breaks console input into tokens using whitespace delimiters and provides typed utility methods to parse primitives directly:

import java.util.Scanner;

Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("You are " + age + " years old");

The Classic Scanner Newline Bug

A notorious pitfall encountered by every Java developer occurs when combining token-based input methods (like nextInt() or nextDouble()) with line-based input (nextLine()):

Scanner sc = new Scanner(System.in);
System.out.print("Enter Roll No: ");
int roll = sc.nextInt(); // Reads integer, but leaves '\n' in the input stream buffer!

System.out.print("Enter Name: ");
String name = sc.nextLine(); // Immediately consumes the leftover '\n' and returns an empty string!
The Fix:

Always insert an extra sc.nextLine(); call after calling nextInt()/nextDouble() to flush the trailing newline character before reading subsequent text lines.

3.3 BufferedReader for Faster Input

While Scanner is convenient, it is noticeably slow because it utilizes complex regular expression parsing and does little buffering. For competitive programming or data-intensive applications parsing hundreds of thousands of lines, BufferedReader wrapped around an InputStreamReader is significantly faster.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class FastIO {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter number: ");
        String line = br.readLine();
        int val = Integer.parseInt(line);
        System.out.println("Square: " + (val * val));
    }
}

Why BufferedReader Outperforms Scanner

  • 8KB Memory Buffer: BufferedReader reads large character blocks (default 8,192 characters) from the operating system stream into memory at once, minimizing costly OS system calls.
  • No Regex Overhead: Scanner runs regular expressions over tokens, consuming CPU cycles. BufferedReader simply reads raw text lines.
  • Synchronized: BufferedReader methods are synchronized, making it thread-safe.
KEY TERM: Scanner vs. BufferedReader

Use Scanner when simplicity and readability matter more than raw speed — it's ideal for learning and for small programs. Reach for BufferedReader when you're processing large volumes of input and performance genuinely matters.

MODULE COMPREHENSIVE QUIZ

Module 3 Final Quiz

Test your understanding across all 3 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 3 Final Quiz →
Yukti Mascot