5 Difference between BufferedReader and Scanner class in Java? Example

Hello guys, welcome to my blog. Today, we'll discuss another interesting Java interview question, BufferedReader vs Scanner. It's not only important from an interview point of view but also to work efficiently with Java. Even though both BufferedReader and Scanner can read a file or user input from the command prompt in Java, there are some significant differences between them. One of the main differences between BufferedReader and Scanner class is that the former class is meant to just read String or text data while the Scanner class is meant to both read and parse text data into Java primitive types like int, short, float, double, and long.

In other words, BufferedRedaer can only read String but Scanner can read both String and other data types like int, float, long, double, float, etc. This functional difference drives several other differences in their usage, which we'll see in this article.

Another difference is Scanner is newer than BufferedReader, only introduced in Java 5, while BufferedReader is present in Java from JDK 1.1 version. This means, you have access to BufferedReader in almost all JDK versions mainly Java 1.4 but Scanner is only available after Java 5.

This is also a popular core Java question from interviews. Since many developers lack Java IO skills, questions like this test their knowledge about API and how to do some practical tasks.

You will not only learn about those key differences between BufferedReader and Scanner in this article but also about how to use them in a Java program. Btw, if you are new in the Java development world, I suggest you first start with a comprehensive course is like The Complete Java Masterclass on Udemy. 

It's very affordable and you can get it under $10 sometimes. The course is really nice and updated for the latest Java version, and I recommend it to both beginners and intermediate developers who want to learn Java in depth.



1. BufferedReader vs Scanner in Java

Anyway, let's get back to the topic.

Here are the 5 key differences between the Scanner and BufferedReader class of Java API:

1. A scanner is a much more powerful utility than BufferedReader. It can parse the user input and read an int, short, byte, float, long, and double apart from String. On the other hand, BufferedReader can only read String in Java.

2. BuffredReader has a significantly large buffer (8KB) than Scanner (1KB), which means if you are reading long String from a file, you should use BufferedReader but for short input and input other than String, you can use Scanner class.

3. BufferedReader is older than Scanner. It's present in Java from JDK 1.1 onward but Scanner is only introduced in JDK 1.5 release.

4. Scanner uses regular expression to read and parse text input. It can accept custom delimiter and parse text into primitive data type e.g. int, long, short, float or double using nextInt(), nextLong(), nextShort(), nextFloat(), and nextDouble() methods, while BufferedReader  can only read and store String using readLine() method.

5. Another major difference between BufferedReader and Scanner class is that BufferedReader is synchronized while Scanner is not. This means, you cannot share Scanner between multiple threads but you can share the BufferedReader object.

This synchronization also makes BufferedReader a little bit slower in the single-thread environment as compared to Scanner, but the speed difference is compensated by Scanner's use of regex, which eventually makes BufferedReader faster for reading String. You can further check these Java Programming online courses to learn more about that in-depth.

5 Difference between BufferedReader and Scanner class in Java







2. Scanner and BufferedReader Example in Java

Though both BufferedReader and Scanner can be used to read a file, Scanner is usually used to read user input and BufferedReader is commonly used to read a file line by line in Java.

One reason for this is Scanner's ability to read String, int, float, or any other data type and BufferedReader's larger buffer size which can hold big lines from a file in memory.

Though it's not a restriction and you can even read a file using Scanner in Java. Alternatively, you can even read a file in just one line of code in Java 8.

If you like books, you can also read Core Java Volume 2 - Advanced Features by Cay S. Horstmann to learn more about Java IO fundamentals. It's one of the key areas in core Java programming which separate an intermediate Java developer from an expert one.


2. 1 Java Program to use Scanner and BufferedReader

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 * Java Program to demonstrate how to use Scanner and BufferedReader class in
 * Java.
 *
 * @author WINDOWS 8
 *
 */
public class ScannerVsBufferedReader{

    public static void main(String[] args) {

        // Using Scanner to read user input
        Scanner scnr = new Scanner(System.in);
        System.out.println("=======================================");
        System.out.println("You can use Scanner to read user input");
        System.out.println("=======================================");
        System.out.println("Please enter a String");
        String name = scnr.nextLine();
        System.out.println("You have entered " + name);
        System.out.println("Please enter an integer");
        int age = scnr.nextInt();
        System.out.println("You have entered " + age);

        scnr.close();

        // Using BufferedReader to read a file
        System.out.println("=======================================");
        System.out.println("You can use BufferedReader to read a file");
        System.out.println("=======================================");
        FileReader fileReader;
        try {
            fileReader = new FileReader("abc.txt");
            BufferedReader buffReader = new BufferedReader(fileReader);

            System.out.println("File contains following lines");
            String line = buffReader.readLine();

            while (line != null) {
                System.out.println(line);
                line = buffReader.readLine();
            }

            buffReader.close();
            fileReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output
=======================================
You can use Scanner to read user input
=======================================
Please enter a String
James
You have entered James
Please enter an integer
32
You have entered 32
=======================================
You can use BufferedReader to read a file
=======================================
File contains following lines
1. Which is best SmartPhone in the market?
a) iPhone 6S
b) Samsung Galaxy Edge
c) Something else

You can see that Scanner is capable of reading both String and numeric data from the command lines. You can also see how easy it is to read a file line by line using BufferedReader.

Here is a summary of all the differences between Scanner and BufferedReader in Java:

Scanner vs BufferedReader in Java


That's all about the difference between Scanner and BufferedReader classes in Java. Even though both are capable of reading user input from the console, you should use Scanner if an input is not big and you also want to read different types of input like int, float, and String. Use BufferedReader is you want to read the text without parsing. Since it has a larger buffer, you can also use it to read long String in Java.


Related Articles
  • 2 ways to read a text file in Java? (solution)
  • How to read an Excel file in Java? (solution)
  • How to read a CSV file in Java? (example)
  • How to create a file and directory in Java? (answer)
  • How to read an XML file in Java? (answer)
  • How to append text to an existing file in Java? (example)
  • 5 Free Java 8 and Java 9 Courses for Programmers (courses)
  • 5 Free Data Structure and Algorithm Courses (courses)
  • 5 Free courses to learn Spring Core and Spring Boot for Java developers (courses)
  • 10 tips to become a better Java developer (tips)

Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. If you want to keep in touch follow me on Twitter, my id is javinpaul.

4 comments:

  1. Thank you for the article. Very educational!

    ReplyDelete
    Replies
    1. Thanks for your comment @Unknown, glad you find it useful.

      Delete
  2. Very useful for fresher and experienced too. many java devs including me don't know this.
    Thank you 😊..!

    ReplyDelete
    Replies
    1. Thanks, so glad that you find my tutorials and articles worth reading.

      Delete

Feel free to comment, ask questions if you have any doubt.