User Input in Java — Scanner BufferedReader Tutorial
Chapter 02 · Java Programming Series
PBA Institute 12 min read Beginner 2024

User Input in Java

User input is the bridge between a Java program and the real world. Java provides several classes such as Scanner, BufferedReader and Console to read values from the keyboard. Mastering input handling is the very first step toward building interactive command line applications.

Key Features

⌨️

Scanner Class

The most common way to read user input. Located in java.util package.

📥

BufferedReader

Fast, buffered character input from the keyboard or any Reader source.

🔢

Typed Methods

Methods like nextInt(), nextDouble(), nextLine() for typed reading.

🛡️

Input Validation

Always validate input to avoid InputMismatchException at runtime.

💬

Console Class

Use System.console() for password input with readPassword().

Performance

BufferedReader is faster than Scanner for large input streams.

Syntax

  • Import the Scanner class with import java.util.Scanner;
  • Create a Scanner object: Scanner sc = new Scanner(System.in);
  • Use sc.nextInt(), sc.nextLine(), sc.nextDouble() to read values.
  • Always close the scanner with sc.close() when done.

Common Scanner Methods

MethodDescriptionReturnsExample
nextInt()Reads an integerintint n = sc.nextInt();
nextDouble()Reads a decimaldoubledouble d = sc.nextDouble();
nextLine()Reads full lineStringString s = sc.nextLine();
next()Reads single tokenStringString w = sc.next();
nextBoolean()Reads booleanbooleanboolean b = sc.nextBoolean();
nextLong()Reads long valuelonglong l = sc.nextLong();

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind User Input in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Read an Integer From User
import java.util.Scanner;

class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        System.out.println("You entered: " + n);

        sc.close();
    }
}
Output Enter a number: 25
You entered: 25

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Read Name & Age
import java.util.Scanner;

class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.println("Hello " + name + ", age " + age);
    }
}
Output Enter your name: John
Enter your age: 22
Hello John, age 22
Sum of Two Numbers
import java.util.Scanner;

class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int a = sc.nextInt();

        System.out.print("Enter second number: ");
        int b = sc.nextInt();

        int sum = a + b;

        System.out.println("Sum = " + sum);
    }
}
Output Enter first number: 10
Enter second number: 15
Sum = 25
Using BufferedReader
import java.io.*;

class Main
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter city: ");
        String city = br.readLine();

        System.out.println("City entered: " + city);
    }
}
Output Enter city: Mumbai
City entered: Mumbai
Read a Double Value
import java.util.Scanner;

class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter price: ");
        double price = sc.nextDouble();

        double tax = price * 0.18;

        System.out.println("Tax = " + tax);
    }
}
Output Enter price: 1000
Tax = 180.0

Notes & Tips

  • Always call sc.nextLine() after sc.nextInt() if you plan to read a string next — to consume the newline character.
  • Closing a Scanner that wraps System.in also closes System.in. Be careful in large programs.
  • BufferedReader.readLine() always returns a String — convert manually with Integer.parseInt().
  • Use a try-with-resources block to ensure Scanner is closed automatically.
  • For password input, prefer System.console().readPassword() over Scanner.

Real-World Use Cases

CLI Applications

Command-line tools that ask the user for filenames, options or settings.

Mini Games

Console games such as Tic-Tac-Toe, number guessing, hangman.

Calculators

Read numbers and operators from the keyboard to compute results.

Data Entry

Quick scripts that load records into arrays or databases from user input.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Write a program that reads two numbers and prints their product.
  • Q2. Read a student's name and three marks, then print the average.
  • Q3. Take a sentence as input and print its length using length().
  • Q4. Read a temperature in Celsius and convert it to Fahrenheit.
  • Q5. Read 5 numbers in a loop and print the largest one.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Which class is most commonly used to read user input in Java?
The Scanner class from java.util is the most common — it offers typed methods like nextInt() and nextLine().
Q2 Difference between Scanner and BufferedReader?
Scanner is easier and offers typed methods; BufferedReader is faster but reads everything as String and may throw IOException.
Q3 Why does nextLine() sometimes skip input after nextInt()?
Because nextInt() leaves a newline character in the buffer which nextLine() immediately consumes.
Q4 How do you read a password securely?
Use System.console().readPassword() which returns a char[] and does not echo characters.
Q5 Can Scanner read from a file?
Yes. Pass a File object to its constructor: new Scanner(new File("data.txt")).

FAQ

FAQ 1 What is the use of Scanner in Java?
Scanner is used to read user input from the keyboard, files, or strings. It parses primitive types and strings using regular expressions.
FAQ 2 Is Scanner thread-safe?
No, Scanner is not thread-safe. For multi-threaded input you must synchronize access manually.
FAQ 3 Which is faster, Scanner or BufferedReader?
BufferedReader is generally faster because it does less parsing and uses internal buffering for character data.
FAQ 4 Can I take input without importing any package?
You can use System.in.read() without importing, but it returns one byte at a time which is inconvenient.
FAQ 5 What is InputMismatchException?
It is thrown when the input does not match the expected type, e.g., entering text where nextInt() expects an integer.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with User Input in Java:

  • Forgetting the semicolon ; at the end of statements while using User Input.
  • Mixing up similar method names — read Java docs before using new APIs related to User Input.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Introduction If Else OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving User Input — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
User InputUser Input conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Introduction — strengthens your understanding of the previous building block.
NEXT If Else — the natural progression after mastering User Input.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Java provides multiple ways to take user input — Scanner is the most beginner friendly, BufferedReader is faster, and Console is ideal for secure password input. Always validate input and close your input streams. Practice with small programs like calculators and games to build confidence.

Continue Learning