Input and Output

Thinking

Handling user input and displaying output is fundamental in creating interactive programs. Java provides flexible mechanisms for reading input from users and printing output to the console or files.

Understanding how to use classes like Scanner and BufferedReader helps you build applications that interact dynamically with users or data sources.

Description

Java provides two common ways to perform input:

  • Scanner: Part of java.util, easy to use for reading input from the keyboard. Methods like nextLine(), nextInt(), and nextDouble() are used.
  • BufferedReader: Part of java.io, suitable for reading larger inputs. It works with InputStreamReader and requires exception handling.

For output, System.out.print and System.out.println are used to display information on the console.

Video Resources

Java Scanner Tutorial

Learn how to use Scanner for console input in Java.

Examples (code)

Using Scanner for Input


import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = input.nextLine();
        System.out.println("Hello, " + name + "!");
        input.close();
    }
}
  

Using BufferedReader for Input


import java.io.*;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your age: ");
        String age = reader.readLine();
        System.out.println("You are " + age + " years old.");
    }
}
  

Real-World Applications

Form Handling

Used in user registration forms and data input interfaces in console applications.

Data Entry Systems

Reading values from users for storing in files or databases.

CLI Applications

Command-line tools that require user commands and arguments use input classes.

Interview Questions

Q1: What is the difference between Scanner and BufferedReader?

Show Answer

Scanner is easier to use for parsing primitives and strings with built-in methods, while BufferedReader is faster and suitable for reading lines or large chunks of text.

Q2: Why should you close Scanner or BufferedReader?

Show Answer

Closing releases the underlying system resources (like input streams) to prevent memory leaks or locking issues.

Q3: Can Scanner read input from files?

Show Answer

Yes, Scanner can read from files using new Scanner(new File("filename")) by importing java.io.File and handling exceptions.