Output Operations
System.out.println
public class OutputDemo {
public static void main(String[] args) {
// println - prints with newline
System.out.println("Hello, World!");
System.out.println(42);
System.out.println(3.14);
System.out.println(true);
// print - prints without newline
System.out.print("Hello ");
System.out.print("World!");
System.out.println(); // newline
// System.err - error output (red text in IDE)
System.err.println("Error occurred!");
}
}
printf (Formatted Output)
public class PrintfDemo {
public static void main(String[] args) {
String name = "Amazon";
int age = 25;
double salary = 150000.50;
// Basic formatting
System.out.printf("Name: %s%n", name);
System.out.printf("Age: %d%n", age);
System.out.printf("Salary: $%.2f%n", salary);
// Width and alignment
System.out.printf("%10s%10d%15.2f%n", name, age, salary);
// Output: " Amazon 25 150000.50
// Left-align with -
System.out.printf("%-10s%-10d%15.2f%n", name, age, salary);
// Output: "Amazon 25 150000.50
// Leading zeros
System.out.printf("%05d%n", 42); // 00042
// Hex, octal, binary
System.out.printf("Hex: %x%n", 255); // ff
System.out.printf("Octal: %o%n", 255); // 377
// Boolean
System.out.printf("Active: %b%n", true); // true
// Character
System.out.printf("Char: %c%n", 'A'); // A
}
}
Format Specifiers
%s - String
%d - Integer (decimal)
%f - Floating-point
%e - Scientific notation
%b - Boolean
%c - Character
%o - Octal
%x - Hexadecimal
%n - Newline (platform-independent)
%% - Literal percent sign
String Concatenation
// Using + operator (simple but creates intermediate strings)
String name = "Amazon";
int year = 2024;
String message1 = name + " " + year; // "Amazon 2024"
// Using concat()
String message2 = name.concat(" ").concat(String.valueOf(year));
// Using String.join()
String joined = String.join("-", "2024", "01", "15"); // "2024-01-15"
// StringBuilder for multiple concatenations (more efficient)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i).append(" ");
}
String result = sb.toString(); // "0 1 2 3 4 5 6 7 8 9 "
Scanner Class
Reading User Input
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read string
System.out.print("Enter name: ");
String name = scanner.nextLine();
// Read integer
System.out.print("Enter age: ");
int age = scanner.nextInt();
// Read double
System.out.print("Enter salary: ");
double salary = scanner.nextDouble();
System.out.printf("%s is %d years old, earns $%.2f%n", name, age, salary);
scanner.close();
}
}
Scanner Methods
import java.util.Scanner;
public class ScannerMethods {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// nextLine() - reads entire line
String line = sc.nextLine();
// next() - reads token (until whitespace)
String token = sc.next();
// nextInt(), nextLong(), nextDouble(), nextFloat()
int num = sc.nextInt();
// hasNext(), hasNextInt(), etc. - check before reading
if (sc.hasNextInt()) {
int n = sc.nextInt();
}
// Common issue: nextLine() after nextInt()
int age = sc.nextInt();
sc.nextLine(); // consume leftover newline!
String name = sc.nextLine();
sc.close();
}
}
Reading from String
import java.util.Scanner;
public class StringScanner {
public static void main(String[] args) {
String data = "10 20 30 40 50";
Scanner sc = new Scanner(data);
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
sc.close();
}
}
File Reading with Scanner
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileScanner {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
BufferedReader
BufferedReader for Fast Input
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Read string
System.out.print("Enter name: ");
String name = br.readLine();
// Read integer (must parse)
System.out.print("Enter age: ");
int age = Integer.parseInt(br.readLine());
System.out.printf("%s is %d years old%n", name, age);
br.close();
}
}
BufferedReader vs Scanner
// BufferedReader is faster for large inputs
public class SpeedComparison {
public static void main(String[] args) throws IOException {
// Scanner (slower, more features)
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // auto-parsing
// BufferedReader (faster, manual parsing)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine()); // manual parsing
// For competitive programming, use BufferedReader
// For simple programs, Scanner is fine
}
}
Reading Multiple Values
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class MultipleValues {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Read space-separated values
String[] parts = br.readLine().split(" ");
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[1]);
System.out.println("Sum: " + (a + b));
br.close();
}
}
File Reading with BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReader {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
Try-with-Resources
// Auto-closes resources
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// br automatically closed here
When to Use Each
I/O Method Selection Guide
| Scenario | Recommended | Why |
|---|---|---|
| Simple output | System.out.println | Easy to use |
| Formatted output | System.out.printf | Control formatting |
| Simple user input | Scanner | Easy parsing |
| Competitive programming | BufferedReader | Faster for large inputs |
| File reading | BufferedReader | Efficient line-by-line |
| Error output | System.err | Separate error stream |
Performance Comparison
// Slow: String concatenation in loop
String result = "";
for (int i = 0; i < 10000; i++) {
result += i; // creates new String each time!
}
// Fast: StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i); // modifies same buffer
}
String result = sb.toString();
// Faster: BufferedReader + StringBuilder for input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder input = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
input.append(line).append("\n");
}
Common Patterns
// Read array from input
public static int[] readArray(BufferedReader br, int n) throws IOException {
int[] arr = new int[n];
String[] parts = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(parts[i]);
}
return arr;
}
// Read 2D grid
public static int[][] readGrid(BufferedReader br, int rows, int cols) throws IOException {
int[][] grid = new int[rows][cols];
for (int i = 0; i < rows; i++) {
String[] parts = br.readLine().split(" ");
for (int j = 0; j < cols; j++) {
grid[i][j] = Integer.parseInt(parts[j]);
}
}
return grid;
}
Practice Problems
Read n numbers from input and print their sum.
Example:
Input: 5 1 2 3 4 5
Output: 15
Sum of 1+2+3+4+5 = 15
Optimal Solution — O(n) time, O(n) space
Read n, then read n numbers and sum them
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] parts = br.readLine().split(" ");
long sum = 0;
for (int i = 0; i < n; i++) {
sum += Long.parseLong(parts[i]);
}
System.out.println(sum);
}
}Edge Cases:
- Large numbers requiring long
- Single element
Print a formatted table of student names and scores.
Example:
Input: Alice 95 Bob 87 Charlie 92
Output: Name Score Alice 95 Bob 87 Charlie 92
Format each row with fixed width columns
Optimal Solution — O(n) time, O(1) space
Use printf for formatted output
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.printf("%-10s%10s%n", "Name", "Score");
System.out.println("-".repeat(20));
String line;
while ((line = br.readLine()) != null && !line.isEmpty()) {
String[] parts = line.split(" ");
System.out.printf("%-10s%10s%n", parts[0], parts[1]);
}
}
}Edge Cases:
- Long names
- Variable score lengths
Quiz
1. Which method reads an entire line of input?
2. Why should you call scanner.nextLine() after scanner.nextInt()?
3. What is the primary purpose of Input and Output?
4. What is a common mistake when implementing Input and Output?
Flashcards
Question
What is the difference between System.out.print and println?
Click to reveal answer
Answer
print outputs without newline, println outputs with newline at the end.
Question
When should you use BufferedReader over Scanner?
Click to reveal answer
Answer
Use BufferedReader for competitive programming or when reading large inputs, as it's faster than Scanner.
Question
What is try-with-resources?
Click to reveal answer
Answer
A Java feature that automatically closes resources (like BufferedReader) when the try block exits, even if an exception occurs.
Question
What is Input and Output?
Click to reveal answer
Answer
Input and Output is a key concept in Java programming.
Question
When to use Input and Output?
Click to reveal answer
Answer
Use Input and Output when building production systems that require reliability, scalability, and maintainability.
Revision Notes
Key Takeaways
- 1.Use System.out.printf for formatted output
- 2.Scanner is easier, BufferedReader is faster
- 3.Always close scanners and readers
- 4.Use try-with-resources for automatic cleanup
- 5.Consume newline after nextInt() with Scanner
Interview Tips
- •Practice reading input quickly for coding challenges
- •Know when to use Scanner vs BufferedReader
- •Use printf for formatted output in problems
- •Handle input parsing exceptions
Cheat Sheet
I/O Cheat Sheet
Output:
System.out.println("text"); // with newline
System.out.print("text"); // without newline
System.out.printf("%s %d%n", str, num); // formatted
Input (Scanner):
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int n = sc.nextInt();
Input (BufferedReader - faster):
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int n = Integer.parseInt(br.readLine());
Format Specifiers:
%s string, %d int, %f float, %b boolean, %n newline