Java
Module 2: Java Fundamentals, Variables & Data TypesBeginner18 min read

Console Input & Output (Scanner & BufferedReader)

Read user input cleanly using Scanner and BufferedReader, format console output with printf, and avoid the classic nextLine() buffer pitfall.

Key Takeaways & Core Concepts
  • | Built-in nextInt(), nextDouble(), nextLine() | Only readLine() (parse with Integer.parseInt) |
  • | 1 KB | 8 KB |
  • | Slower (uses regex tokenization) | Much faster (ideal for large inputs) |
  • | No | Throws IOException |

Introduction

Interactive CLI tools and coding-challenge solutions read from standard input (System.in) and write formatted output to System.out. Choosing the right reader impacts both ergonomics and throughput.

Formatted Output & Safe Scanner Reading
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner("98\nRiya Sharma");
6 int marks = sc.nextInt();
7 sc.nextLine(); // Consume leftover newline!
8 String name = sc.nextLine();
9
10 System.out.printf("Student: %-12s | Marks: %d/100%n", name, marks);
11 sc.close();
12 }
13}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: `%-12s` left-aligns the string in a 12-character column, and `%n` prints a platform-independent newline.

Scanner vs BufferedReader

Featurejava.util.Scannerjava.io.BufferedReader
Ease of UseBuilt-in nextInt(), nextDouble(), nextLine()Only readLine() (parse with Integer.parseInt)
Buffer Size1 KB8 KB
SpeedSlower (uses regex tokenization)Much faster (ideal for large inputs)
Checked ExceptionsNoThrows IOException

Classic Pitfall: nextInt() Followed by nextLine()

sc.nextInt() reads the digits but leaves the trailing newline \n in the input buffer. Calling sc.nextLine() immediately after consumes that leftover newline and returns an empty string! Always add an extra sc.nextLine(); after numeric reads before reading a full line, or read everything via nextLine() and parse with Integer.parseInt(...).

Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)