Input and Output
Scanner, BufferedReader, System.out
Interview Relevant: Handling user input and output is fundamental
8 min read
Output in Java
Printing output to the console is one of the first things you learn in Java.
System.out Methods
System.out.println()- Prints and adds a newlineSystem.out.print()- Prints WITHOUT adding newlineSystem.out.printf()- Formatted output (like printf in C)
Input in Java
Reading user input can be done in multiple ways:
1. Scanner Class (Recommended)
Most commonly used, easy to parse various data types:
2. BufferedReader
Efficient for reading lines of text:
3. Console Class
For interactive console applications:
ā ļø Memory Leak Warning: Always close Scanner/BufferedReader after use with .close() or try-with-resources statement!
Code Examples
Different output methods in Java
java
1// Output examples
2System.out.println("Hello, World!"); // Prints with newline
3System.out.print("No newline"); // No newline
4System.out.println("Next line"); // On new line
5
6// Formatted output
7System.out.printf("Name: %s, Age: %d%n", "John", 25);Using Scanner for user input (most common approach)
java
1import java.util.Scanner;
2
3Scanner sc = new Scanner(System.in);
4
5System.out.print("Enter your name: ");
6String name = sc.nextLine(); // Read entire line
7
8System.out.print("Enter your age: ");
9int age = sc.nextInt(); // Read integer
10
11System.out.print("Enter height: ");
12double height = sc.nextDouble(); // Read double
13
14sc.close(); // Always close to avoid memory leaks!Using BufferedReader for efficient line input
java
1import java.io.*;
2
3BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
4
5String line = br.readLine(); // Reads entire line as String
6br.close();Best practice: using try-with-resources for automatic resource cleanup
java
1// Try-with-resources (automatically closes)
2try (Scanner sc = new Scanner(System.in)) {
3 System.out.print("Enter text: ");
4 String text = sc.nextLine();
5 System.out.println("You entered: " + text);
6} // Scanner automatically closed here!Use Cases
- Creating interactive console programs
- Reading user input for processing
- Displaying formatted output to users
- Debugging by printing variable values
- Creating command-line applications
Common Mistakes to Avoid
- Not closing Scanner/BufferedReader (memory leak)
- Forgetting to handle InputMismatchException
- Mixing nextLine() with nextInt() (causes issues)
- Not converting String input to appropriate types
- Reading more input than provided by user