Buffered Reader Input

April 11, 2016, by Hamid Siddiqui

/**
 * @author Hamid Siddiqui
 * https://github.com/inventionsbyhamid
 * https://www.quora.com/profile/Hamid-Siddiqui
 *
 * @program To use BufferedReader for taking input from user
 *
 * While using BufferedReader we should import the java.io.* package and
 * throws IOException against the function definition which has any input operation or use try, catch block.
 * Below code uses throws IOException for the same.
 * BufferedReader is fast for input operations and should be preferred over Scanner
 */

import java.io.*;

class BufferInput {

    public static void main(String args[]) throws IOException {
        //create BufferedReader object named k, object can be named anything
        BufferedReader k = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter string");
        //input String
        String s = k.readLine();
        System.out.println("String = " + s);

        System.out.println("Enter integer");
        //input int, k.readLine() takes input as String as above, Integer.parseInt() converts the string to int
        int n = Integer.parseInt(k.readLine());
        System.out.println("int = " + n );

        System.out.println("Enter integer");
        //input long
        long l = Long.parseLong(k.readLine());
        System.out.println("long = " + l);

        System.out.println("Enter decimal number");
        //input double
        double d = Double.parseDouble(k.readLine());
        System.out.println("double = " + d);

        System.out.println("Enter decimal number");
        //input float
        float f = Float.parseFloat(k.readLine());
        System.out.println("float = " + f);




    }
}
Sample Input/Output

Enter string
Hamid
String = Hamid
Enter integer
1234
int = 1234
Enter integer
123456789234
long = 123456789234
Enter decimal number
12345.1234
double = 12345.1234
Enter decimal number
124.456
float = 124.456




Scanner Input →

← Hello World