Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java User Input - Scanner Class
Next article icon

Java User Input - Scanner Class

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

The most common way to take user input in Java is using the Scanner class. It is a part of java.util package. The scanner class can handle input from different places, like as we are typing at the console, reading from a file, or working with data streams. This class was introduced in Java 5. Before that, we used the BufferedReader class (introduced in Java 1.1). As a beginner, we will suggest to use Scanner class.

Using Scanner in Our Code

Follow these steps to take user input using Scanner class:

  • Import the Scanner class using import java.util.Scanner;
  • Create the Scanner object and connect Scanner with System.in by passing it as an argument i.e., Scanner sc = new Scanner(System.in);
  • When we want to ask the user for input, first print a prompt message so they know what to enter. Then use one of Scanner's handy methods to read the response:
    • nextInt() for whole numbers
    • nextLine() for full text lines
    • nextDouble() for decimal numbers
    • next() for single words

Example: Let us go through a simple example where we get two numbers from the user and add them together:

Java
// Taking user input import java.util.Scanner;  class Geeks  {     public static void main(String[] args)     {          // Creating Scanner class object         Scanner scn = new Scanner(System.in);          // Enter first input         System.out.print("Enter First Number: ");         int a = scn.nextInt();          System.out.print("Enter Second Number: ");         int b = scn.nextInt();          System.out.println("Sum: " + (a + b));          // Closing the scanner to release resources         scn.close();     } } 

Output:

Output


Methods of Scanner Class

We have discussed few methods of Scanner class above, but the Scanner class provides some more methods to read different data types, let us discuss those in the below table:

Method

Description

                          nextBoolean()                       

Used for reading Boolean value.

nextByte()

Used for reading Byte value.

nextDouble()

Used for reading Double value.

nextFloat()

Used for reading Float value.

nextInt()

Used for reading Int value.

nextLine()

Used for reading Line value.

nextLong()

Used for reading Long value.

nextShort()

Used for reading Short value.


Example: Here, we are taking multiple user inputs like string, float, double etc. and using the above mentioned methods of Scanner Class.

Java
// Taking multiple user input using Scanner Class import java.util.Scanner;  public class Geeks {     public static void main(String[] args)     {         // Scanner definition         Scanner scn = new Scanner(System.in);          // input is a string(one word)         System.out.print("Enter a word: ");         String str1 = scn.nextLine();         System.out.println("Entered String str1: " + str1);          // input is a string(complete sentence)         System.out.print("Enter a sentence: ");         String str2 = scn.nextLine();         System.out.println("Entered String str2: " + str2);          // input is an integer         System.out.print("Enter an integer: ");         int x = Integer.parseInt(scn.nextLine());         System.out.println("Entered Integer: " + x);          // input is a float value         System.out.print("Enter a float value: ");         float f = Float.parseFloat(scn.nextLine());         System.out.println("Entered FloatValue: " + f);          scn.close();     } } 

Output:

Output
2


Another method to take user input is using BufferedReader Class. It is a simple class that is used to read a sequence of characters. It provides several methods, including:

  • read(): Reads a single character.
  • read(char[] cbuf): Reads an array of characters.
  • readLine(): Reads an entire line of text.

To know more about BufferedReader Class, please refer to the article - BufferedReader Class in Java


BufferedReader vs Scanner Class

AspectsBufferedReaderScanner
Primary UseEfficient reading of character streams.Reading formatted input (e.g., integers, strings).
SpeedFaster for large input as it does less parsing.Slower due to parsing overhead (e.g., nextInt(), nextFloat()).
Exception HandlingThrows checked exceptions (e.g., IOException).No checked exceptions; easier to use.
FlexibilityAllows reading larger input efficiently.Best suited for reading simple data types.
Thread SafetySynchronized, making it thread-safe.Not thread-safe by default.
Common UseUsed for reading large input efficiently.Commonly used for smaller, formatted input.

Next Article
Java User Input - Scanner Class

R

rexsunar37010
Improve
Article Tags :
  • Java
  • java-basics
Practice Tags :
  • Java

Similar Reads

    Scanner Class in Java
    In Java, the Scanner class is present in the java.util package is used to obtain input for primitive types like int, double, etc., and strings. We can use this class to read input from a user or a file. In this article, we cover how to take different input values from the user using the Scanner clas
    6 min read
    Java BufferedReader vs Scanner Class
    Java provides several classes for reading input, but two of the most commonly used are Scanner and BufferedReader. The main difference between Scanner and BufferedReader is:Scanner class provides parsing and input reading capabilities with built-in methods for different data types.BufferedReader cla
    2 min read
    Scanner useRadix() method in Java with Examples
    The useRadix(radix) method of java.util.Scanner class sets this scanner's default radix to the specified radix. A scanner's radix affects elements of its default number matching regular expressions. Syntax: public Scanner useRadix(int radix) Parameters: The function accepts a mandatory parameter rad
    2 min read
    Java Reader Class
    Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
    6 min read
    Java.io.LineNumberInputStream Class in Java
    java.io.LineNumberInputStream class is simply an extension of input stream providing a extra facility to keep the record of current line number. Line is a sequence of bytes ending with : '\r' i.e. a carriage return character or a newline character : '\n', or a linefeed character following the carria
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences