How to Take Input in Java from User

In this tutorial, we will learn how to take input in Java from the user or keyboard.

There are two ways by which we can take or accept input in Java from the user or from a file.

  • BufferedReader Class
  • Scanner Class

BufferedReader class


BufferedReader is a subclass of Reader class that is used to read a sequence of characters. It provides a readLine() method to read an array of characters, strings, and text lines.

It adds the buffer to the underlying input stream, so that there is no need to access the underlying file system for each read and write operation. BufferedReader class may throw checked exceptions.

Let’s create a Java program to take a string as an input from the user or keyboard using BufferedReader class.

Program code 1:

package javaProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TakeInput {
public static void main(String[] args) throws IOException 
{
// Create an InputStreamReader object using a standard input stream.
   InputStreamReader isr = new InputStreamReader(System.in);	
// Create BufferedReader object to take input from the keyboard.
   BufferedReader br = new BufferedReader(isr); // Wrapping input stream reader into buffered reader.
   
// Prompt to enter a string from the user. 
   System.out.println("Enter your first name: ");
   String firstName = br.readLine(); // reading data.
   System.out.println("Enter your last name: ");
   String lastName = br.readLine();
   String fullName = firstName +" " + lastName;
   System.out.println("Full name: " +fullName);
   }
}
Output:
      Enter your first name: 
      Ivaan
      Enter your last name: 
      Sagar
      Full name: Ivaan Sagar

In this example, we have used readLine() method of BufferedReader class to accept input from the keyboard or user. The readLine() accepts a string from the keyboard and returns a string.

This method can throw a runtime exception named IOException that must be handled using a throws clause or try-catch block.

How to take Integer Input in Java using BufferedReader?


Let’s create a Java program to take integer value as an input from the user or keyboard using BufferedReader class.


Program code 2:

package javaProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TakeInput {
public static void main(String[] args) throws IOException 
{
// Create an InputStreamReader object using a standard input stream.
   InputStreamReader isr = new InputStreamReader(System.in);	
// Create BufferedReader object to take input from the keyboard.
   BufferedReader br = new BufferedReader(isr);
   
// Prompt to enter an integer value from the user. 
   System.out.println("Enter an int value: ");
   String data = br.readLine(); // reading data.
   int num = Integer.parseInt(data);
// Displaying int value.   
   System.out.println("You entered a value: " +num);
   }
}
Output:
      Enter an int value: 25
      You entered a value: 25

In this example, we have accepted an integer number as a string, using readLine() method as:

String data = br.readLine();

Since the number is in the form of string, we will need to convert it into int by using parseInt() method of Integer class. The code is:

int num = Integer.parseInt(data);

If needed, we can combine and write the above two statements as:

int num = Integer.parseInt(br.readLine());

Here, parseInt() is a static method in an Integer class. Therefore, we can call it using its class name.


Let us understand some important points here.

1. Here, we have not used type casting to convert String type to int type because String is a class and int is a fundamental data type.

Converting a class type into fundamental data type is not possible by using type casting. It is possible only by using a method parseInt() of Integer class.


2. Remember that type casting is useful to convert one fundamental data type to another fundamental data type or one class type to another class type. We cannot exercise type casting to convert a class type into a fundamental data type or vice versa.

How to take Float input in Java from User?


Let’s create a Java program to take float value as an input from the user by using BufferedReader class.

Program code 3:

package javaProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TakeInput {
public static void main(String[] args) throws IOException 
{
// Create an InputStreamReader object using a standard input stream.
   InputStreamReader isr = new InputStreamReader(System.in);	
// Create BufferedReader object to take input from the keyboard.
   BufferedReader br = new BufferedReader(isr);
   
// Prompt to enter a float value from the user. 
   System.out.println("Enter a float value: ");
   String data = br.readLine(); // reading data.
   float num = Float.parseFloat(data);
// Displaying float value.   
   System.out.println("You entered a value: " +num);
   }
}
Output:
      Enter a float value: 99.99
      You entered a value: 99.99

In this example, we are taking a float value as a string and then passing string data to Float.parseFloat() to convert it into a float.

The parseFloat() is a static method in Float class. Thus, just like an integer value, we can also take a float value from the keyboard or user.

Accepting a Double value from Keyboard


We can accept a double value as input from the keyboard by using the following statement:

double num = Double.parseDouble(br.readLine());

Here, we are accepting a double value as a string using br.readLine() method of BufferedReader class. Then, we are passing the string to Double.parseDouble() to convert it into primitive type double. We know that parseDouble() is a static method in Double class.

Taking Other Types of Input Values from User


Similarly, we can write different statements to take input of many other data types from the user as follows:

1. To take a byte value:

byte num = Byte.parseByte(br.readLine());

Here, br is the reference variable of BufferedReader class object.

2. To take a short value as an input:

short num = Short.parseShort(br.readLine());

3. To accept a long value as an input:

long num = Long.parseLong(br.readLine());

4. To take a boolean value as an input:

boolean x = Boolean.parseBoolean(br.readLine());

In the above discussion, we have used classes, such as Boolean, Byte, Short, Integer, Long, Float, and Double , which belong to java.lang package. These classes are known as wrapper classes in Java.

How to Take a Single Character from the Keyboard?


Let’s create a Java program to take a single character as an input from the keyboard using BufferedReader class.

Program code 4:

package javaProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TakeInput {
public static void main(String[] args) throws IOException 
{
 InputStreamReader isr = new InputStreamReader(System.in);	
 BufferedReader br = new BufferedReader(isr);
   
// Prompt to enter a single character as an input from the user. 
   System.out.println("Enter a character: ");
// Reading a single character from the user using read() method.
   int data = br.read();
   char ch = (char)data; // type casting.
// Displaying a single character.   
   System.out.println("You entered a character: " +ch);
   }
}
Output:
      Enter a character: X
      You entered a character: X

In this example, we have used read() method of BufferedReader class to read a single character from the keyboard or user. But, this method returns its ASCII number, which is an integer value.

Since we cannot store this number in a char type variable ch, we have converted int data type into char data type by using type casting.

Converting one data type to another data type is called type casting or simply casting in Java.

The read() method throws a runtime exception named IOException due to some reason (like insufficient memory or illegal character). We should handle it using a throws clause or try-catch block. This is called exception handling in Java.

How to Take Input in Java using Scanner class?


We can use a Scanner class of java.util package to take or read an input from the user, keyboard, or a text file. When a Scanner class takes an input, it breaks the input into many pieces, called tokens.

We can retrieve these tokens from the Scanner object by using the following methods:

  • next() – to read a string.
  • nextByte() – to read a byte value.
  • nextInt() – to read an integer value.
  • nextFloat() – to read a float value.
  • nextLong() – to read a long value.
  • nextDouble() – to read a double value.

To read or accept an input from the user, we can use Scanner class as:

Scanner sc = new Scanner(System.in);

In the above statement, we are passing System.in to the Scanner class constructor. System.in represents InputStream object, which represents a standard input device, i.e. keyboard by default.

System is simply a class found in java.lang package and in is a field in the System class.


Let us write a Java program to take or read different types of input data separated by space, from the keyboard (i.e. user) using Scanner class.

Program code 5:

package javaProgram;
import java.io.IOException;
import java.util.Scanner;
public class TakeInput {
public static void main(String[] args) throws IOException 
{
 System.out.print("Enter name, rollNo, and marks: ");
 Scanner sc = new Scanner(System.in);
 String name = sc.next();
 int rollNo = sc.nextInt();
 float marks = sc.nextFloat();
 System.out.println("Name: " +name);
 System.out.println("Roll no: " +rollNo);
 System.out.println("Marks obtained: " +marks);
  }
}
Output:
      Enter name, rollNo, and marks: Deepak 10 79.89
      Name: Deepak
      Roll no: 10
      Marks obtained: 79.89

In this example, we have entered a string, integer, and float values from the keyboard. These data are stored into Scanner object sc as a token.

To retrieve these tokens, we have used methods, such as sc.next(), sc.nextInt(), and sc.nextFloat(). Then, we have displayed these values on the console.

Difference between BufferedReader and Scanner in Java


The difference between BufferedReader and Scanner in Java is as follows:

1. BufferedReader is suitable for reading long strings, while Scanner is better for short inputs.

2. The performance of BufferedReader is faster than Scanner because it does not perform any parsing operations.

3. BufferedReader is more suitable for reading a file, while Scanner is suitable for parsing a file.

4. By default, BufferedReader uses the buffer of 8 KB, while Scanner uses the buffer of 1 KB.

5. BufferedReader is synchronized, while Scanner is not.

6. A Scanner can use the BufferedReader, but the opposite is not possible.

7. BufferedReader class is present in java.io package, while Scanner class is present in java.util package.


In this tutorial, you learned how to take input from the user or keyboard in Java in different ways. Hope that you will have understood the basic concepts of taking input from the user and practiced all programs. In the next, we will understand the how to format output in Java using printf.

Please email us if you find anything incorrect in this tutorial. Your email will be valuable to us.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love