Programs

How to get User Input In Java [With Examples]

Introduction

Taking user input in Java is the first step towards creating successful software in Java. The Java program collects input from the user through various input sources such as a mouse, keyboard, network request, CLI arguments, etc. Java also has various I/O packages that can be imported into the program to perform input-output operations. These packages support input of primitive types like double, integer, strings, etc.

This article will focus on methods like Scanner, BufferedReader, and InputStreamReader to take user input in Java.

Check out our free courses to get an edge over the competition.

How to Take Input in Java using the Scanner Class?

The Scanner class is one of the methods in the “java.util” package that parses and handles all the primitive type inputs. The Scanner class asks the user to enter the input, and then it prints the same on the screen or console. You can import the Scanner class from the “java.util” package in the program and create an object to use its methods.

For example,

Scanner test = new Scanner(System.in);

In the above statement, the test is the name of an object, and System.in is the input stream. The Scanner instance created will scan the user input in Java.

Check out upGrad’s Java Bootcamp

Note: It is not necessary to write System.in as the input string in your program. You can replace it with a file and a file to read, string as the input stream.

For example,

Scanner test = new Scanner(new FileInputStream(“testFile.txt”), “UTF-8”);

Make sure that you write code {test.close()} to close the scanner when you are done editing it.

Scanner Methods for Reading Inputs from User

The following table lists the methods that the scanner uses to read the input in Java entered by the user.

Method Return Type Description
Next() String Returns the next token from the Scanner
nextByte() Byte Reads the next input as a byte.
nextFloat() Float Reads the next input as a float.
nextInt() Integer Reads the next input as an integer.
nextShort() Short Read the next input as a short.
nextLong() Long Read the next input as a long.
nextBoolean() Boolean Reads the next input as a Boolean and returns the value.
nextLine() String Advances the scanner one line and returns the input skipped.

 Example

The following Java program uses the Scanner class to take user input in Java (string, integer, and afloat).

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

import java.util.Scanner;

 class TakeUserInput

{

  public static void main(String args[])

  {

  int a;

  float b;

  String c;

   Scanner test = new Scanner(System.in);

   //Take user input as String

     System.out.println(“Type a string: “);

  c = in.nextLine();

     System.out.println(“User Input String is: “+c);

   //Take user input as Integer

     System.out.println(“Type an integer: “);

  a = in.nextInt();

     System.out.println(“User Input Integer is: “+a);

   //Take user input as float

     System.out.println(“Type a float number: “);

  b = in.nextFloat();

     System.out.println(“User Input Float number is: “+b);

  }}

Output

Type a string:

Andrew

User Input String is: Andrew

Type an integer:

03

User Input Integer is: 03

Type a float number:

61.46

User Input Float number is: 61.46

If you want to learn more about taking input in Java using the scanner class, check out the Multiple String Input in Java using the Scanner blog.

BufferedReader and InputStreamReader Methods

BufferedReader is another class in Java that scans the stream of characters from a character-based input stream. InputStreamReader is a function in Java that converts the input stream into a sequence of characters for BufferedReader to scan. The BufferedReader class accepts the InputStream as a parameter.

The BufferedReader class uses read() and readLine() methods to read characters and the next line and returns them.

You must import the java.io.BufferedReader package to create a BufferedReader class.  

// Creates a FileReader

FileReader test = new FileReader(String file);

// Creates a BufferedReader

BufferedReader a = new BufferedReader(test);

Get Software Engineering degrees online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

BufferedReader Methods for Reading Inputs from User

The following table lists the methods that the buffered reader uses to read the input in Java entered by the user.

Method Description
ready() Verifies if the file reader is in a read state.
mark() Marks the position in the buffered reader up to which the data has been read.
reset() Returns the control to the point where the mark was set.

Example

The following Java program uses a BufferedReader class alongside an InputStreamReader class to take the user input in Java.

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class test {

 public static void main(String[] args) {

  BufferedReader buffer = null;

  try {

   String scanFirstLine;

   buffer = new BufferedReader(new FileReader(“D:\\user_input.txt”));

   while ((scanFirstLine = buffer.readLine()) != null) {

    System.out.println(scanFirstLine);

   }

  } catch (IOException a) {

   a.printStackTrace();

  } finally {

   try {

    if (buffer != null)

     buffer.close();

   } catch (IOException b) {

    b.printStackTrace();

   }  } } }

Output

The following data is found in the file:

This is a sample statement that BufferedReader reads from the file.

In the above example, we created a buffered reader named buffer. The buffered reader is linked with the “user_input.txt” file.

Then, we used the readLine() method to scan the characters from the buffer of the buffered reader.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

Conclusion

In this article, we have covered the methods used to take user input in Java. We have discussed the Scanner and BufferedReader methods, along with examples. We have also discussed the methods that Scanner and BufferedReader class uses to take input in Java. We hope that you have got a basic understanding of how to handle input in Java. If you want to learn more Java programming language, check out upGrad’s Executive PG Program in Full Stack Development course designed for working professionals.  

Why should you learn Java?

Java is a user-friendly language and ideal for students learning any programming language. As a language, Java helps you get down on the coding ground and find your way in the infinite software world. Additionally, Java is very versatile and flexible. Java is compatible with any operating system. Due to the pandemic, people have started using their personal devices like laptops, desktops, etc., for work. Java language is designed to work on any OS such as Mac, Windows, iOS, and Android. Moreover, in the future, Java will continue to be in demand. Mobile app downloads in 2020 have increased to 150 billion and will soon touch the 184 billion mark. Most Android applications have back-end code written in Java. The number of downloads determines the number of applications on the phone, creating more room for Java. This explains how Java will continue to dominate other programming languages in the future.

How much does a Java developer make?

The average Java developer salary in India is INR 4,97,611/year. As an entry-level Java developer, the numbers could vary. The salary of a Java developer also fluctuates based on their experience. The more they experience, the more they get paid. A developer is mainly focused on creating web applications that are then sold in the market. They are a part of a software development team aiming to design, maintain, write, and implement code. Having a bachelor’s in IT or computer science can help you kickstart your journey as a Java professional.

Which area uses Java the most?

Java has the ability to work on every platform. Furthermore, it is also free to use and an object-oriented program. Java has been taken by inspiration from the C and C++ languages. It was created to keep it easy for beginners. Some areas that widely use Java are game development, stock market algorithms, open-source development, machine learning, and artificial intelligence.

Want to share this article?

Plan Your Software Development Career Now.

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks