EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Java

Input/Output in Java

Java provides multiple ways to take input from users through its I/O (Input/Output) package. These streams facilitate the reading of characters, data types, and objects from input devices such as keyboards or files. The most common ways to capture user input in Java are through the BufferedReader class and the Scanner class.

Methods to Take Input in Java

There are two primary ways to get input from the user or a file in Java:

1. Using BufferedReader Class
2. Using Scanner Class

1. Using BufferedReader Class to Take Input in Java

The BufferedReader class is part of Java’s I/O package and is used for reading streams of characters. The readLine() method of this class reads input as a string. InputStreamReader is often used in conjunction with BufferedReader to convert byte streams into character streams, enabling character-based input reading.

Note: BufferedReader can throw checked exceptions, which need to be handled using try-catch blocks or by declaring them with throws.

Example of Taking Input Using BufferedReader:

import java.io.*;

public class InputExample {
    public static void main(String[] args) throws IOException {
        // Creating a BufferedReader object
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        // Reading string input
        System.out.println("Enter a string:");
        String str = reader.readLine();

        // Reading integer input
        System.out.println("Enter an integer:");
        int num = Integer.parseInt(reader.readLine());

        // Output the values
        System.out.println("Entered String: " + str);
        System.out.println("Entered Integer: " + num);
    }
}

Output:

Enter a string:
John Doe
Enter an integer:
123
Entered String: John Doe
Entered Integer: 123

Alternative Example of BufferedReader Input:

import java.io.*;

public class Example {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter your name:");
            String name = reader.readLine();  // Reading string input
            System.out.println("Name: " + name);
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Sample Output:

Enter your name:
John
Name: John

2. Using Scanner Class for Taking Input in Java

The Scanner class is an advanced and user-friendly input class that is part of Java’s util package. It simplifies input handling by providing various methods like nextInt()nextFloat()next(), and nextLine(). These methods allow you to directly capture input without explicit parsing.

Advantages of Scanner:

  • Easier to use than BufferedReader.
  • Supports multiple data types (integers, floats, strings, etc.) directly.
  • No need for throws declarations as no checked exceptions are thrown.
  • Provides methods to read formatted input easily.

Example of Taking Input Using Scanner:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        // Create Scanner object
        Scanner sc = new Scanner(System.in);

        // Input a String (single word)
        String word = sc.next();
        System.out.println("Entered word: " + word);

        // Input a String (full sentence)
        sc.nextLine();  // Clear the buffer
        String sentence = sc.nextLine();
        System.out.println("Entered sentence: " + sentence);

        // Input an Integer
        int num = sc.nextInt();
        System.out.println("Entered Integer: " + num);

        // Input a floating-point number
        float f = sc.nextFloat();
        System.out.println("Entered Float: " + f);
    }
}

Output:

John
Hello World
123
45.67
Entered word: John
Entered sentence: Hello World
Entered Integer: 123
Entered Float: 45.67

Another Example:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter your name:");
        String name = sc.nextLine();

        System.out.println("Enter your roll number:");
        int rollNo = sc.nextInt();

        System.out.println("Enter your marks:");
        float marks = sc.nextFloat();

        // Output the entered data
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNo);
        System.out.println("Marks: " + marks);
    }
}

Output:

Enter your name:
Alice
Enter your roll number:
10
Enter your marks:
89.5
Name: Alice
Roll Number: 10
Marks: 89.5

Differences Between BufferedReader and Scanner

1. BufferedReader is a basic way to read input, typically used for reading streams of characters. It is faster than Scanner as it doesn’t perform any post-processing or parsing.
2. Scanner is more user-friendly for simple input, especially when you need to read different data types. However, Scanner is slower because it performs input parsing internally (like nextInt(), nextFloat()).
3. BufferedReader allows you to specify the size of the input stream to be read, making it more flexible when handling large input.
4. BufferedReader is synchronized, making it suitable for multi-threaded applications, while Scanner is not.
5. Scanner is typically preferred for smaller inputs due to its simplicity, while BufferedReader is favored for larger inputs due to better performance.

End of lesson.