BufferedReader Vs Scanner Class In Java

BufferedReader Vs Scanner Class In Java
BufferedReader Vs Scanner Class In Java

Introduction

As we know, Java is an object-oriented programming language; hence everything is structured or wrapped into objects and classes. Unlike C or C++, Java does not have cin and scanf() for taking the input from the user in the Command line(console). Nevertheless, Java has several input methods like Scanner Class, BufferedReader Class, Command line Argument, and Console Class.

Firstly let’s master the significant differences in bufferreader vs scanner class in Java. Afterwards, we’ll be exploring the rest of the input methods. These classes belong to the java.util and java.io packages. 

Get ready to take the input from the console!

Scanner Class in Java

Scanner class is a built-in class in java that allows the user to take the input from the console. It was introduced in theory K 1.5 version onwards. As the name suggests, a scanner class scans across each line in something. That could be the console or when you type in as the argument.

The Scanner class scans the primitive data types like int, float, long, double, short, and byte. Many programmers find this way as most straightforward among all the other methods.

Syntax:

scanner sc = new scanner (System.in);

java.util.Scanner is a package in the Java API used to create a Scanner object. It generates an InputMismatchException if the input does not match the expected data type. Wrap your code inside the try and catch block to validate the user’s input.

The above statement creates the constructor of the Scanner Class with the default argument as a System.in which plays the role of reading from the standard input stream,i.e., from the keyboard. We also have a System.out which points to the screen.

Here sc is the name of our object, and it can be anything. There are tons of methods residing in the Scanner Class. Let’s discuss them one by one. 

Note: 

  • Make sure to import the package java.util.Scanner into your program before making the Scanner object; else, you will be encountering compile-time errors.
  • As Java is a case-sensitive language, make sure you spell the keywords correctly as it is.

Methods of Scanner Class

As we’ve learned above Scanner scans primitive types like int, float, short, and so on.

There are inbuilt methods for each data type. The scanner class contains other methods which assist in taking the input. Although along with advantages Scanner Class has disadvantages as well. We’ll be discussing that later in this lesson itself.

Using Scanner class

import java.util.Scanner; //Imported the package which contains the Scanner Class

public class ScannerClass {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the data \n");
int data = sc.nextInt(); // nextInt() is a method which assist in taking the integer data from the user.
		
		System.out.println("Your entered data "+data); // printing the entered data 
	}

}

Output:

Enter the data 
7
Your entered data 7
MethodDescription
public String next()it returns the next token from the scanner class.
public String nextLine()it moves the Scanner position to the next line and returns the value as a string
public byte nextByte()it reads the next token as a byte.
public int nextInt()it reads the next token as an int.
public float nextFloat()it reads the next token as a float.
public short nextShort()it reads the next token as a short.
public long nextLong()it reads the next token as a long.
public double nextDouble()it reads the next token as a double.
public boolean nextBoolean()it reads the boolean value.

Other input methods

public class ScannerClass {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter the double data ");
		double num = sc.nextDouble(); 
		System.out.println("Double data: "+num);
		
		System.out.print("Enter the float data ");
		float num2 = sc.nextFloat();
		System.out.println("Float data: "+num2);
		
		System.out.print("Enter the byte data ");
		byte num3 = sc.nextByte();
		System.out.println("Byte data: "+num3);
		
		System.out.print("Enter the short data ");
		short num4 = sc.nextShort();
		System.out.println("Short data: "+num4);
		
	}
 }

Output:

Enter the double data 78695.9865
  Double data: 78695.9865
  Enter the float data 7.6
  Float data: 7.6
  Enter the byte data 76
  Byte data: 76
  Enter the short data 6754
  Short data: 6754

As you can see, we haven’t taken the string input yet. Let’s take it now, and there is a crucial thing to notice.

String input can quickly be taken from the user if the buffer is free,i.e., there is only string input at the very start of the code. But what if not? If there is any other method before the string method that could be nextInt() or nextFloat() or any nextXxx() method, then nextLine() would be skipped.

It is the major drawback of Scanner Class. It is not the case in the BufferedReader class. It’s the significant difference in bufferreader vs. scanner class in java.

Explanation using code

public class ScannerClass {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter the integer data : ");
		int x = sc.nextInt();
		System.out.println(x);
		
		System.out.println("Enter the string : ");
     	String str = sc.nextLine();
		System.out.println(str);
		
		System.out.println("Enter the second string : ");
     	String str2 = sc.nextLine();
		System.out.println(str2);
		
	}
 }

Output:

Enter the integer data : 
 100
 100
 Enter the string : 

 Enter the second string : 
 I love Coding Ninjas
 I love Coding Ninjas

The problem is that after entering the numerical value, the first sc.nextLine() is skipped and the second sc.nextLine() executed as shown in the above output. That’s because the sc.nextInt() method does not read the newline character in your input created by hitting “Enter,” and so the call to sc.nextLine() returns after reading that newline.

You will encounter a similar behavior when you use sc.nextLine() after sc..next() or any sc.nextXxx() method (except nextLine() itself).

Either put an sc.nextLine() call after each sc.nextInt() or sc.nextFoo to consume the rest of that line ,including newline.

Or, even better, read the input through sc.nextLine() and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method. It will throw the NumberFormatException.

Explanation Using Code

public class ScannerClass {

	public static void main(String[] args)  {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter the integer data : ");
		int x = sc.nextInt();
		System.out.println(x);
		System.out.println("Enter the string : ");
		sc.nextLine();// This line you have to add (It consumes the   \n character)
     	String str = sc.nextLine();
		System.out.println(str);
		
		System.out.println("Enter the second string : ");
     	String str2 = sc.nextLine();
		System.out.println(str2);
		
	}}

Output:

Enter the integer data : 
 78
 78
 Enter the string : 
 I love Coding Ninjas
 I love Coding Ninjas
 Enter the second string : 
 I Love Coding
 I Love Coding

BufferedReader class in Java

BufferedReader is another way to take the input from the user, but it’s a bit more complex than the Scanner class. java.io.BufferedReader reads text from the character-input stream.

It was introduced in Java from the jdk 1.1 version onwards. Using readLine(), it reads the data line by line. It makes the performance fast. Correspondingly, it inherits the Reader class if you wish to read the data from the file.

BufferedReader is a bit faster than Scanner as Scanner does the parsing of input data, and BufferedReader simply reads the sequence of characters.

In the case of a File Reading, BufferedReader stores the small portion of data that depends on the buffer size; for instance, when a user reads the data, it picks up the following immediate amount of data from the file. BufferedReader acts as a medium. It makes the performance fast. We can specify the size of the buffer. 

Typically, each Reader application made with Reader enables a compatible reading request to be made with a primary character or byte stream. Therefore, it is recommended to wrap a BufferedReader around any Reader whose read operations may be costly, such as FileReaders and InputStreamReaders.

Constructors in BufferedReader class

  •   BufferedReader(Reader in): It creates a buffering character-input stream that uses a default-sized input buffer.
  • BufferedReader(Reader in, int size): It creates a buffering character-input stream that uses an input buffer of the specified size.

Methods in BufferedReader class

  • readLine() throws IOException: readLine() reads a line of text. A line is considered to be terminated by any one of a line feed (‘\n’), a carriage return (‘\r’), a carriage return followed immediately by a line feed, r by reaching the end-of-file(EOF).
  • read() throws IOException: read() returns the character read as an integer in the range 0 to 65535, or -1 if the end of the stream has been reached.

Taking the string input from the console

import java.io.*;

public class BufferedReaderclass {

	public static void main(String[] args) throws IOException {
		
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter you string here:");
      String object = bf.readLine();
      System.out.println(object);
	}

}

Output:

Enter your string here:
 I love Coding Ninjas
 I love Coding Ninjas

As discussed above, BufferedReader doesn’t have the inbuilt methods for taking any other input apart from the string. We can parse the String input into our required type. You can refer to the Implementation below to understand the concept of bufferreader vs scanner class in java.

import java.io.*;

public class BufferedReaderclass {

	public static void main(String[] args) throws Exception {
		
      BufferedReader bf = new BufferedReader(new
InputStreamReader(System.in));
      System.out.println("Enter your integer data here:");  
      int x = Integer.parseInt(bf.readLine());
      
      System.out.println("Enter your float data here:");
      float y = Float.parseFloat(bf.readLine());
      
      System.out.println("Enter your string here:");
      String object = bf.readLine();
      
      System.out.println("Cast from string to Integer: "+ x);
      System.out.println("Cast from String to Float: "+ y);
      System.out.println(object);
	}

}

Output:

Enter your integer data here:
 90
 Enter your float data here:
 9.654
 Enter your string here:
 Coding Ninjasss
 Cast from string to Integer: 90
 Cast from String to Float: 9.654
 Coding Ninjasss

Note: While parsing, it will throw the NumberFormatException. Therefore,  wrap in a try-catch block or use the throws keyword immediately after the main method as in the above example.

Image Source: Google

BufferReader vs Scanner class in Java

Scanner classBufferedReader class
The scanner class is not synchronous and does not support threads.The BufferedReader class is synchronous and Widely used with multiple threads.
Scanner breaks its input into tokens using a Delimiter pattern.BufferedReader simply reads the sequence of characters in a portion that depends on the buffer size.
The scanner has a little buffer(1KB byte buffer).It has a significantly larger buffer memory than Scanner.(8KB byte buffer)
The scanner is slow as it does the parsing of input data. Moreover, It hides IOException.Unlike Scanner, BufferedReader simply reads the sequence of characters. Hence it is faster than the Scanner Class. It throws an IOException.

When to use Scanner class and BufferedReader class?

The BufferedReader class is meant to read stream or text data, while the Scanner class is intended to both read and parse the test data into primitive types. The Scanner class has 1KB of buffer size while BufferedReader has 8KB, more significant than the Scanner class.

Therefore, use BufferedReader to get long strings from a stream, and use Scanner if you wish to parse a specific type of token from a stream.

Also, as we have learned in the difference table of bufferreader vs scanner class in java, BufferedReader is synchronised, whereas Scanner class is not synchronised, which means you cannot share Scanner Class between multiple threads. However, you can share BufferedReader objects between multiple threads.

Frequently Asked Questions

Should I use a scanner or BufferedReader in Java?

It always depends on the user’s input regarding using bufferreader vs scanner class in java. BufferedReader has a much larger memory than the Scanner. Use BufferedReader to get longer strings in the stream, then use Scanner class to analyze some type of token from the stream.

What is the difference between a bufferreader vs scanner class in Java?

The scanner can tokenize using a custom delimiter and parse the stream into primitive data types, while BufferedReader can only read and store String.

What is the BufferReader() class in Java?

A BufferedReader is a class that helps in efficiently reading the underlying stream.

Is scanner() slow Java?

Unlike the BufferedReader class, it does the parsing of the input data. Hence it is slow as compared to BufferedReader.

What is the nextLine() method in Java?

nextLine() method is the inbuilt method that resides in the scanner class; it shifts the Scanner position to the next line and returns the value as a string.

Key Takeaways

To sum up bufferreader vs scanner class in java, both the classes help in taking the input from the command line argument(console). BufferedReader only reads the character-stream data, whereas Scanner has a lot more cheese built into it; it can do all that a BufferedReader can do.

The significant difference between them is the buffer size. Irrespective of the buffer size, the scanner does the parsing of the primitive types.

Even if you want to read the character-stream input BufferedReader is good for that. On the other hand, if you want to accept user input with multiple options, Scanner will work best. The disadvantage of the BufferedReader class is that it is hard to remember, whereas the Scanner class is a bit easy.

To read more about the input methods, please refer to our article on “Java knowledge for your first coding job.”

By Alisha Chhabra