Accept input from the keyboard using a stream

  • Last Updated: November 17, 2023
  • By: javahandson
  • Series
img

Accept input from the keyboard using a stream

In this article, we will learn how to accept input from the keyboard using a stream in Java with proper examples. If you want to learn about other Java topics you can click the above Java menu or you can click on this link Java topics.

 

Input is data given to the program to perform some operations and the output is the resultant data which is displayed as a result of the program.

We can give the input directly inside the program like below

package com.java.handson.io;

public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int sum = a + b;
        System.out.println("Sum is : "+ sum);
    }
}
Output: Sum is : 30

In the above program, we have declared a and b variables inside the program. Here a and b are the inputs. If we are executing this program multiple times the same input will be used every time and the same output will be displayed. This program is a kind of static one.

Now instead of hardcoding the values of a and b in the program if we have to get the dynamic values of a and b from the user’s keyboard then can we do it? Yes, we can do that we will see that in the below sections.

To understand how to get the input values from the keyboard we have to first learn about the stream.

What is a Stream?

A stream is a flow of data from one place to another. The System is a class present in java.lang package to denote standard input and output. There are 2 types of streams:

Input stream

The input stream receives the data or reads the incoming data from an input device. Ex. Reading from a keyboard.

System.in represents a standard input device i.e. keyboard which can be used to accept an input. System.in is an InputStream object. We have to pass this InputStream as an argument to the InputStreamReader so as to read the data.

InputStreamReader inputStreamReader = new InputStreamReader(System.in);

We can use InputStreamReader to read the data but it is not that efficient because it reads only one character from the input stream at a time and the rest of the character remains in the stream. So we usually combine the InputStreamReader with the BufferedReader. BufferedReader is also a type of input stream but it reads multiple characters from the stream at once and buffers them so the characters will be readily available for reading and the read process will be more efficient.

InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

The BufferedReader class is having methods like read and readLine to read the incoming data from the keyboard.

Output stream

System.out represents a standard output device i.e. monitor which can be used to display an output. System.out is a PrintStream object. PrintStream is having multiple methods such as print or println to display the output on the monitor.

System.out.print("Java HandsOn");
System.out.println("Java HandsOn");

Accepting a single character from the keyboard

We have to follow the above steps to create a BufferedReader object and then we can use the read method of that BufferedReader object to input a single character from the keyboard. Let’s see it below

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a single character : ");
        int character = bufferedReader.read();

        System.out.println("character entered is : "+character);
    }
}
Output: 
Enter a single character : A
character entered is : 65

In the above program, we have entered the character as ‘A’ but when we sysout the character value the result is 65 because the read method returns an int ASCII value of the character. If we have to convert the ASCII value to char value then we have to perform type casting.

Note* Type casting means converting one data type into another data type. In the above example, we have to convert the int data type to char data type.

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a single character : ");
        char character = (char) bufferedReader.read();
        
        System.out.println("character entered is : "+character);
    }
}
Output:
Enter a single character : A
character entered is : A

We have also written ‘throws IOException’ in the method signature. We will learn more about this in Exception handling articles. But one thing we need to understand is in some cases the input character in the program might not be valid or if we are reading some data from a file and the file is corrupted or if we have reached the end of the file and still we are trying to read that file then in such cases compiler is smart enough to say that either we should handle that exception or throw it back.

So in our above program, we are not handling the exception we are throwing it back hence in such case if such an exception occurs then the program will end abruptly.

Accepting String from the keyboard

In the above section we have seen if we have to read a single character from a keyboard then we should use the read method of the BufferedReader class but now if we have to read a String value then we have to use the readLine method of BufferedReader class.

Note* String is a combination of characters. Ex. Name, Address, etc

Write a program to input the name from the keyboard.

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a name : ");
        String name = bufferedReader.readLine();

        System.out.println("Entered name is : "+name);
    }
}
Output:
Enter a name : JavaHandsOn
Entered name is : JavaHandsOn

In the above example, we do not have to use the type casting because the readLine method will return the String value.

Accepting different datatypes from the keyboard

We will not be able to accept different datatypes from the keyboard instead we can just read the String values from the keyboard and then convert ( or parse ) them into the required datatypes such as integer, float, double, etc.

Accept integer

The parseInt method of the Integer class will help us to convert the String value to int type.

String is a class type and int is a primitive datatype so we cannot convert String directly to int using type casting hence we have to make use of the parseInt method. Please check the example below.

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a integer : ");
        int number = Integer.parseInt(bufferedReader.readLine());

        System.out.println("Entered integer is : "+number);
    }
}
Output:
Enter a integer : 12
Entered integer is : 12

In the above example, we have entered a number 12 and we were successfully able to parse it to int type but suppose instead of passing a number we have passed a String value then what will happen? In such a case, we will get a NumberFormatException because a String value cannot be converted to int. Let us see it below.

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a integer : ");
        int number = Integer.parseInt(bufferedReader.readLine());

        System.out.println("Entered integer is : "+number);
    }
}
Output:
Enter a integer : Java
Exception in thread "main" java.lang.NumberFormatException: For input string: "Java"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.java.handson.io.Test.main(Test.java:15)

Accept float

The parseFloat method of the Float class will help us to convert the String value to float type.

float number = Float.parseFloat(bufferedReader.readLine());

Accept double

The parseDouble method of Double class will help us to convert the String value to double type.

double number = Double.parseDouble(bufferedReader.readLine());

Accept boolean

The parseBoolean method of Boolean class will help us to convert the String value to boolean type.

boolean bool = Boolean.parseBoolean(bufferedReader.readLine());

boolean can have only 2 values true or false but if we input a value other than true or false then the parseBoolean method will convert that value to false.

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a boolean value : ");
        boolean bool = Boolean.parseBoolean(bufferedReader.readLine());

        System.out.println("Entered boolean value is : "+bool);
    }
}
Output:
Enter a boolean value : 12
Entered boolean value is : false

Accepting Student information from the keyboard

Write a program to input the data of a Student from a keyboard such as name, age, sex, etc, and print them on the console.

package com.java.handson.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        System.out.print("Enter a Student name : ");
        String name = bufferedReader.readLine();

        System.out.print("Enter a Student age : ");
        int age = Integer.parseInt(bufferedReader.readLine());

        System.out.print("Enter Student marks : ");
        float marks = Float.parseFloat(bufferedReader.readLine());

        System.out.print("Enter a Student sex : ");
        char sex = (char) bufferedReader.read();

        System.out.println("Student name is : "+ name);
        System.out.println("Student age is : "+ age);
        System.out.println("Student sex is : "+ sex);
        System.out.println("Student marks is : "+ marks);
    }
}
Output:
Enter a Student name : Suraj
Enter a Student age : 33
Enter Student marks : 450.50f
Enter a Student sex : M

Student name is : Suraj
Student age is : 33
Student sex is : M
Student marks is : 450.5

So this is all about how to accept input from the keyboard using a stream in Java. If you have any questions on this topic please raise them in the comments section.

If you liked this article then please share this post and this website with your friends and colleagues so that they can learn Java and its frameworks in more depth.

Leave a Comment