Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 File Class
Next article icon

Scanner Class in Java

Last Updated : 11 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Example 1: Taking input from the user using the Scanner class and displaying the output.

Java
// Java program to demonstrate the use of Scanner class // to take input from user import java.util.Scanner;  class Geeks  {     public static void main(String[] args) {          Scanner sc = new Scanner(System.in);         System.out.println("Enter your name:");         String name = sc.nextLine();          System.out.println("Hello, " + name + " Welcome to the GeeksforGeeks.");      }  } 

Output:

ScannerClassOutput

Explanation: In the above code example, we use the nextLine() of Scanner class to read the line value which is entered by the user and print it in the console.

Steps To Use Scanner Class to Take Input

Step 1: First, import the java.uti.Scanner package in top of the program file Without importing this package, we can not use the Scanner class. either we can import the java.util.* by importing this package we can use all the classes present in the util package.

import java.util.Scanner

public class Geeks{

public static void main(String [] args){

}
}


Step 2: Create the object of the Scanner class.

Scanner sc = new Scanner (System.in);

Here “sc” is an object of the Scanner class. We can give it different names for our ease such as in, var or obj etc. Using this object we can use the methods of the Scanner class.


Step 3: Create a variable and using scanner class object call the corresponding method to take the input value.

int age = sc.nextInt();

Java Scanner Input Types

The scanner class helps take the standard input stream in Java. So, we need some methods to extract data from the stream. The methods used for extracting data are mentioned below:

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

Let us look at the code snippet to read data of various data types.


Example 2: Taking different inputs using Scanner class method such as nextInt(), nextDouble and nextLine(), etc.

Java
// Java program to read data of various types  // using Scanner class import java.util.Scanner;  // Driver Class public class Geeks  {     // main function     public static void main(String[] args) {                  // Declare the object and initialize with         // predefined standard input object         Scanner sc = new Scanner(System.in);          System.out.println("Enter your name:");          // String input         String name = sc.nextLine();          System.out.println("Enter your gender (M/F): ");          // Character input         char gender = sc.next().charAt(0);          // Numerical data input         // byte, short and float can be read          System.out.println("Enter your age: ");         int age = sc.nextInt();          System.out.println("Enter your cgpa: ");         double cgpa = sc.nextDouble();          // Print the values to check if the input was         // correctly obtained.         System.out.println("Name: " + name);         System.out.println("Gender: " + gender);         System.out.println("Age: " + age);          System.out.println("CGPA: " + cgpa);     } } 

Output:

ScannerClassObjectOutput

Explanation: In the above code example, we use the Scanner class to take different types of input values from user and print it in the console.


Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered). Then, we check if the scanner’s input is of the type we want with the help of hasNextDataType() functions where DataType is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).

  • hasNextInt(): This method is used to check if the token is an integer.
  • hasNextLine(): This method is used to check if there is an input in next line.
  • useDelimiter(): This method changes the default whitespace delimiter.


Example 3: Using the hasNext() and hasNextInt() method to take input from user without specifying the limit of input values.

Java
// Java program to read some values using Scanner // class and print their mean. import java.util.Scanner;  public class Geeks  {     public static void main(String[] args) {                  // Declare an object and initialize with         // predefined standard input object         Scanner sc = new Scanner(System.in);          // Initialize sum and count of input elements         int sum = 0, count = 0;          System.out.println("Enter integers to calculate the mean (type 'done' to finish):");          // Loop to read input until "done" is entered         while (sc.hasNext()) {             if (sc.hasNextInt()) {                                  // Read an int value                 int num = sc.nextInt();                 sum += num;                 count++;             } else {                 String input = sc.next();                 if (input.equalsIgnoreCase("done")) {                     break;                 } else {                     System.out.println("Invalid input. Please enter an integer or type 'done' to finish.");                 }             }         }          // Calculate and display the mean         if (count > 0) {             // Use double for precise mean calculation                          double mean = (double) sum / count;              System.out.println("Mean: " + mean);         } else {             System.out.println("No integers were input. Mean cannot be calculated.");         }           } } 

Output:

OutputHasNextMethod

Explanation: In the above code example, we use the hasNext() and hasNextInt() method to take the input values from user and then user give the input value they can specify that the input value is ended and they can type “done” to find the mean value of given input.

Important Points:

  • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
  • To read strings, we use nextLine().
  • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
  • Always close the Scanner object after use to avoid resource leaks.
  • The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: “How are you”
    In this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.


Next Article
Java File Class

S

Sukrit Bhatnagar
Improve
Article Tags :
  • Java
  • Java-I/O
  • Java-Scanner
Practice Tags :
  • Java

Similar Reads

  • Java User Input - Scanner Class
    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
    4 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
    7 min read
  • Java StringTokenizer Class
    StringTokenizer class in Java is used to break a string into tokens based on delimiters. A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a su
    5 min read
  • Java Math Class
    Java.lang.Math Class methods help to perform numeric operations like square, square root, cube, cube root, exponential and trigonometric operations. Declaration public final class Math extends Object Methods of Math Class in JavaMath class consists of methods that can perform mathematical operations
    7 min read
  • Java File Class
    Java File class is a representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, crea
    6 min read
  • Java.lang.System class in Java
    Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. It extends class
    15 min read
  • Java.io.StringReader class in Java
    StringReader class in Java is a character stream class whose source is a string. It inherits Reader Class. Closing the StringReader is not necessary, it is because system resources like network sockets and files are not used. Let us check more points about StringReader Class in Java. Declare StringR
    4 min read
  • Java.io.LineNumberReader class in Java
    A buffered character-input stream that keeps track of line numbers. This class defines methods setLineNumber(int) and getLineNumber() for setting and getting the current line number respectively. By default, line numbering begins at 0. This number increments at every line terminator as the data is r
    4 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 that Scanner Class provides parsing and input reading capabilities with built-in methods for different data types while Buffered
    2 min read
  • Scanner close() method in Java with Examples
    The close() method ofjava.util.Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect. Syntax: public void close() Return Value: The function does not return any value. Below programs illustrate the above function:
    1 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