Scanner Vs BufferedReader

smartjeff

Jeff Odhiambo

Posted on February 15, 2022

Scanner Vs BufferedReader

Taking Input from User

Most of the program often request for data to be processed from the user and most of the programming language if not all provides a mechanism through which a user can enter data to be processed into the computer.

For instance in python its done through the use of input method e.g

name = input("Enter name >>> ")
Enter fullscreen mode Exit fullscreen mode

In C Programming scanf is used e.g,

char name[20];
printf("[+]Enter your name >>> ");
scanf("%s",&name);
Enter fullscreen mode Exit fullscreen mode

How about Java?

In Java, there are two ways of doing it.
Scanner and BufferedReader class are sources that serve as ways of reading inputs. When using scanner, it doesn't through an exception while when using Buffered reader it throws exceptions.

Sample code for the use of the Two

Scanner

import java.util.Scanner;

public class NameReader{
    public static void main(String[] args){
        int Age;
        Scanner input = new Scanner(System.in);
        System.out.print("[+]Enter your Age >>> ");
        Age = input.nextInt();
        System.out.println("Your Age is "+Age);
    }
}
Enter fullscreen mode Exit fullscreen mode

OutPut:

[+]Enter your Age >>> 23
Your Age is 23

Process finished with exit code 0
Enter fullscreen mode Exit fullscreen mode

Buffered Reader

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AgeReader{
    public static void main(String[] args)throws Exception{
        int Age;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("[+]Enter your Age >>> ");
        Age = Integer.parseInt(br.readLine());
        System.out.println("Hello your age is "+Age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

[+]Enter your Age >>> 23
Hello your age is 23

Process finished with exit code 0
Enter fullscreen mode Exit fullscreen mode

These are the two main mechanisms through which users can interact with the computer in Java.

💖 💪 🙅 🚩
smartjeff
Jeff Odhiambo

Posted on February 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Scanner Vs BufferedReader
discuss Scanner Vs BufferedReader

February 15, 2022