Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconHow to get User Input In Java [With Examples]

How to get User Input In Java [With Examples]

Last updated:
27th May, 2021
Views
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
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.

Ads of upGrad blog

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.

MethodReturn TypeDescription
Next()StringReturns the next token from the Scanner
nextByte()ByteReads the next input as a byte.
nextFloat()FloatReads the next input as a float.
nextInt()IntegerReads the next input as an integer.
nextShort()ShortRead the next input as a short.
nextLong()LongRead the next input as a long.
nextBoolean()BooleanReads the next input as a Boolean and returns the value.
nextLine()StringAdvances 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.

MethodDescription
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.

Ads of upGrad blog

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.  

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1Why 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.

2How 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.

3Which 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.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Best Jobs in IT without coding
134101
If you are someone who dreams of getting into the IT industry but doesn’t have a passion for learning programming, then it’s OKAY! Let me
Read More

by Sriram

12 Apr 2024

Scrum Master Salary in India: For Freshers & Experienced [2023]
900289
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers & Experienced [2024]
904975
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5019
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5127
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5046
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5112
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5049
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5124
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon