Java Notes
Complete guide to Java I/O — System.out for output (print, println, printf), Scanner for input, BufferedReader, formatting output, reading different data types, and handling input errors.
Every useful program needs to communicate with users — displaying results (output) and accepting data (input). Java provides multiple ways to handle both, from simple console I/O to formatted output.
Output — Displaying Information
System.out Methods
public class OutputMethods {
public static void main(String[] args) {
// println() — prints with newline at the end
System.out.println("Hello, World!");
System.out.println("Each println starts a new line");
System.out.println(); // blank line
// print() — prints WITHOUT newline (stays on same line)
System.out.print("Hello ");
System.out.print("World ");
System.out.print("Same Line!");
System.out.println(); // manually add newline
// printf() — formatted output (like C's printf)
String name = "Alice";
int age = 25;
double gpa = 3.857;
System.out.printf("Name: %s, Age: %d, GPA: %.2f%n", name, age, gpa);
// String concatenation with +
System.out.println("Name: " + name + ", Age: " + age);
}
}Hello, World! Each println starts a new line Hello World Same Line! Name: Alice, Age: 25, GPA: 3.86 Name: Alice, Age: 25
printf Format Specifiers
Integer: 42 Padded: [ 42] Left: [42 ] Zeros: [0000000042] Float: 3.141590 2 dec: 3.14 Width: [ 3.14] String: Hello Padded: [ Hello] Left: [Hello ] Char: A Boolean: true Science: 1.234568e+05 Line 1 Line 2 ╔══════════╦═══════╦══════════╗ ║ Product ║ Qty ║ Price ║ ╠══════════╬═══════╬══════════╣ ║ Apple ║ 50 ║ $ 1.99 ║ ║ Banana ║ 120 ║ $ 0.59 ║ ║ Cherry ║ 200 ║ $ 4.99 ║ ╚══════════╩═══════╩══════════╝
Input — Reading User Data
Scanner Class (Most Common)
import java.util.Scanner;
public class ScannerInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Reading a String (full line)
System.out.print("Enter your full name: ");
String name = scanner.nextLine();
// Reading an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Reading a double
System.out.print("Enter your GPA: ");
double gpa = scanner.nextDouble();
// Reading a boolean
System.out.print("Are you a student? (true/false): ");
boolean isStudent = scanner.nextBoolean();
// Display results
System.out.println("\n=== Profile ===");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.printf("GPA: %.2f%n", gpa);
System.out.println("Student: " + isStudent);
scanner.close();
}
}Enter your full name: John Smith Enter your age: 22 Enter your GPA: 3.75 Are you a student? (true/false): true === Profile === Name: John Smith Age: 22 GPA: 3.75 Student: true
Scanner Methods Reference
| Method | Reads | Returns |
|---|---|---|
nextLine() | Entire line (until Enter) | String |
next() | Next token (until whitespace) | String |
nextInt() | Next integer | int |
nextLong() | Next long integer | long |
nextDouble() | Next decimal number | double |
nextFloat() | Next float | float |
nextBoolean() | true or false | boolean |
nextByte() | Next byte value | byte |
hasNext() | Checks if more input exists | boolean |
hasNextInt() | Checks if next token is int | boolean |
The nextLine() Problem
import java.util.Scanner;
public class NextLineProblem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// PROBLEM: nextInt() leaves a newline in the buffer
System.out.print("Enter age: ");
int age = sc.nextInt();
// sc.nextLine(); // SOLUTION: consume the leftover newline!
System.out.print("Enter name: ");
String name = sc.nextLine(); // This reads the leftover newline!
// name will be empty!
System.out.println("Age: " + age + ", Name: '" + name + "'");
}
}Enter age: 25 Enter name: Age: 25, Name: ''
Fix: Always add scanner.nextLine() after nextInt()/nextDouble() if you plan to read a line next:
import java.util.Scanner;
public class NextLineFix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt();
sc.nextLine(); // ← CONSUME THE LEFTOVER NEWLINE
System.out.print("Enter name: ");
String name = sc.nextLine(); // Now works correctly!
System.out.println("Age: " + age + ", Name: '" + name + "'");
sc.close();
}
}Enter age: 25 Enter name: Alice Age: 25, Name: 'Alice'
Input Validation
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Validate integer input
int age = 0;
while (true) {
System.out.print("Enter age (1-120): ");
if (sc.hasNextInt()) {
age = sc.nextInt();
if (age >= 1 && age <= 120) {
break;
}
System.out.println("Age must be between 1 and 120!");
} else {
System.out.println("Invalid! Please enter a number.");
sc.next(); // consume the invalid input
}
}
System.out.println("Valid age entered: " + age);
sc.close();
}
}Enter age (1-120): abc Invalid! Please enter a number. Enter age (1-120): 150 Age must be between 1 and 120! Enter age (1-120): 25 Valid age entered: 25
BufferedReader (Alternative — Faster for Large Input)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedReaderInput {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = br.readLine();
System.out.print("Enter your age: ");
int age = Integer.parseInt(br.readLine()); // must parse manually
System.out.print("Enter your salary: ");
double salary = Double.parseDouble(br.readLine());
System.out.printf("%s, age %d, earns $%.2f%n", name, age, salary);
}
}Enter your name: Bob Enter your age: 30 Enter your salary: 75000.50 Bob, age 30, earns $75000.50
Scanner vs BufferedReader
| Feature | Scanner | BufferedReader |
|---|---|---|
| Parse types | Built-in (nextInt, nextDouble) | Manual (Integer.parseInt) |
| Speed | Slower | Faster (buffered) |
| Ease of use | Easier | More code |
| Thread safety | Not synchronized | Synchronized |
| Best for | Simple programs, competitive coding | Large input, production code |
| Buffer size | 1KB | 8KB (configurable) |
Practical Example: Student Grade Calculator
╔════════════════════════════════╗ ║ Student Grade Calculator ║ ╚════════════════════════════════╝ Enter student name: Alice Johnson Enter number of subjects: 3 Enter marks for subject 1 (0-100): 85 Enter marks for subject 2 (0-100): 92 Enter marks for subject 3 (0-100): 78 ┌─── Report Card ───────────────┐ │ Student: Alice Johnson │ │ Total: 255.0 │ │ Average: 85.00 │ │ Grade: A │ └───────────────────────────────┘
Common Mistakes
- Not consuming the newline after nextInt() —
nextInt()leaves\nin the buffer. CallnextLine()to consume it before reading a line. - Not closing the Scanner — while not critical for System.in, it's good practice. Use try-with-resources:
try (Scanner sc = new Scanner(System.in)) { ... }. - Not validating input — users can enter anything. Always validate with
hasNextInt()or try-catch aroundparseInt. - Using
next()whennextLine()is needed —next()reads only one word (until whitespace). For full lines with spaces, usenextLine(). - Confusing
%nand\nin printf —%nis platform-independent (\r\n on Windows, \n on Unix). In printf, prefer%n. In println/print,\nis fine.
Interview Questions
Q1: What is the difference between print(), println(), and printf()?
Answer: print() outputs text without a newline. println() outputs text followed by a newline (moves cursor to next line). printf() outputs formatted text using format specifiers (%d, %s, %f) for precise control over alignment, precision, and formatting.
Q2: What is the nextLine() bug with Scanner and how do you fix it?
Answer: When nextInt()/nextDouble() reads a number, it leaves the newline character (\n) from pressing Enter in the input buffer. The subsequent nextLine() reads this leftover newline and returns an empty string. Fix: Call scanner.nextLine() immediately after nextInt()/nextDouble() to consume the leftover newline.
Q3: What is the difference between Scanner and BufferedReader?
Answer: Scanner is simpler (auto-parses types, has nextInt()/nextDouble()). BufferedReader is faster (8KB buffer vs 1KB), thread-safe, and better for large input but requires manual parsing (Integer.parseInt()). For competitive programming and performance-critical apps, BufferedReader is preferred.
Q4: How do you format a floating-point number to 2 decimal places?
Answer: Use System.out.printf("%.2f", value) or String.format("%.2f", value). The .2 specifies 2 digits after the decimal point. This rounds the value for display without changing the actual variable.
Q5: How can you read input from a file instead of the console?
Answer: Scanner can accept a File object: Scanner sc = new Scanner(new File("input.txt")). You can then use the same methods (nextInt(), nextLine(), etc.) to read from the file. Remember to handle FileNotFoundException.
Summary
Java provides System.out (print, println, printf) for output and Scanner/BufferedReader for input. Use printf with format specifiers for precise formatting, Scanner for simple interactive input, and BufferedReader for performance. Always validate user input and be aware of the nextLine() buffer issue. These I/O fundamentals are the foundation for building interactive Java programs.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Input and Output in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, syntax, basics
Related Java Master Course Topics