Table of contents
1.
Introduction
2.
What is Scanner Class?
2.1.
Java Scanner Class Declaration
3.
How to Get Java Scanner?
4.
Java Scanner Class Constructors
5.
Java Scanner Class Methods
6.
Working of Java Scanner Class
7.
Example of Using Scanner Class in Java
7.1.
Java
8.
Advantages of Scanner Class in Java
9.
Drawbacks of Scanner Class in Java
10.
Important Points About Java Scanner Class
11.
Frequently Asked Questions
11.1.
How to Import the Scanner Class in Java?
11.2.
Is Scanner Class a Superclass in Java?
11.3.
What is the next Method in Scanner Class?
11.4.
How to take string input in Java using the scanner class?
12.
Conclusion
Last Updated: Oct 11, 2024
Easy

Scanner Class in Java

Author Rhythm Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Scanner class in Java is a versatile utility that simplifies user input and data reading from various sources. It allows for easy parsing of primitive types and strings, making it ideal for console applications and file handling. With its user-friendly methods for reading different data types, tokenization, and built-in error checking, the Scanner class enhances coding efficiency.

scanner class in java

This article will explore its features and provide practical examples for effective usage.

What is Scanner Class?

The Scanner class in Java is a part of the java.util package and is used for obtaining input of primitive types like int, double, etc., and strings from the user or a file. It provides various methods to parse and process input, making it versatile for reading different types of data. By creating an instance of the Scanner class and associating it with an input source like System.in, developers can easily interact with users through console input.

Java Scanner Class Declaration

To declare a Scanner class object in Java, you typically use the following syntax:

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

This creates a Scanner object named scanner that is associated with the standard input stream (System.in), allowing you to read user input from the console.

How to Get Java Scanner?

To use the Scanner class in Java, you need to import it from the java.util package. You can then create an instance of the Scanner class by calling its constructor and passing an input source, such as System.in for console input or a file input stream for reading from files.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

This creates a Scanner object named scanner that is ready to read input from the console.

Java Scanner Class Constructors

The Scanner class in Java provides several constructors to initialize a Scanner object with different input sources. These include:

ConstructorDescription
Scanner(InputStream source)Initializes a Scanner to read from an input stream, such as System.in.
Scanner(File source)Initializes a Scanner to read from a specified file.
Scanner(String source)Initializes a Scanner to read from a string.
Scanner(Readable source)Initializes a Scanner to read from any object that implements the Readable interface.
Scanner(Path source)Initializes a Scanner to read from a specified file path.

These constructors allow flexibility in setting up the Scanner object to read input from various sources, including standard input, files, strings, or custom readable objects.

Java Scanner Class Methods

From the beginning of the article, we have seen that the Scanner class in Java is used to take user inputs.

Now, an input may be of any type. It may be a character, or an integer or even a fractional number. So, is the method of taking inputs then different for different kinds of inputs?

Yes, it is, and this is where Scanner class methods (like nextLine in Java) come into play. 

The following table shows the different scanner class methods in Java and where they are used.

MethodDescription
nextInt()Takes integer input from the user.
nextFloat()Takes floating-point input from the user.
nextBoolean()Takes boolean input from the user.
nextLine()Takes a line of text (with spaces) as input from the user.
next()Takes character input from the user.
nextByte()Takes a byte value as input from the user.
nextDouble()Takes double-type input from the user.
nextShort()Takes short-type input from the user.
nextLong()Takes long-type input from the user.

Working of Java Scanner Class

  1. Import the Scanner Class: First, import the Scanner class from the java.util package into your Java program.
  2. Create Scanner Object: Initialize a Scanner object by calling one of its constructors, specifying the input source from which you want to read data. Common sources include System.in for console input or a File object for reading from files.
  3. Read Input: Use various methods provided by the Scanner class, such as nextInt(), nextDouble(), nextLine(), etc., to read input of different data types from the specified source.
  4. Process Input: Process the input data as needed within your program. You can perform calculations, validations, or any other operations based on the input received.
  5. Close the Scanner: After reading all the necessary input, it's good practice to close the Scanner object using the close() method to release system resources associated with it and prevent resource leaks.

Example of Using Scanner Class in Java

Let us consider a code, where some information like name, age, salary and mood of a user are asked and stored. Since we are taking inputs from the user, we will have to use the Scanner class.

  • Java

Java

import java.util.Scanner;     //importing Scanner class

public class Main

{

public static void main(String args[])

{

   Scanner sc=new Scanner(System.in); //creating scanner object

   System.out.print("Enter your full name: ");

   String name = sc.nextLine(); //String input

   System.out.print("Enter your age: ");

   int age = sc.nextInt(); //integer input

   System.out.print("Enter your salary: ");

   double salary = sc.nextDouble(); //double-type input

   System.out.print("Are you happy today? True/False: ");

   boolean mood = sc.nextBoolean(); //boolean input

   System.out.println();

   System.out.println("Name: "+name+"\nAge: "+age+"\nSalary: "+salary+"\nHappy? "+mood);

}

}
You can also try this code with Online Java Compiler
Run Code

Output:

Enter your full name: Neha Sharma

Enter your age: 25

Enter your salary: 10000

Are you happy today? True/False: true




Name: Neha Sharma

Age: 25

Salary: 10000.0

Happy? true

 

To explore more about the Scanner Class, you can visit the Java official documentation here.

Advantages of Scanner Class in Java

  • Ease of Use: The Scanner class simplifies input handling by providing convenient methods for reading different data types, such as integers, strings, and floating-point numbers.
     
  • Versatility: It can read input from various sources, including user input via the console, files, and streams, making it a flexible option for input operations.
     
  • Tokenization: The Scanner class can parse input into tokens, allowing for easy extraction of individual words or numbers from a line of text.
     
  • Error Handling: It provides built-in error checking, such as handling invalid input types, which helps in preventing runtime exceptions and improves robustness.
     
  • Locale Support: The Scanner class supports different locales, enabling it to handle input formats that vary by region, such as number formatting and date representations.

Drawbacks of Scanner Class in Java

There are many methods to take inputs from the user, apart from the Scanner class. All of these methods come with their advantages and disadvantages. 

The disadvantages you may face with the Scanner class are:

  1. The Scanner class is not thread-safe.
     
  2. It has less buffer memory (1KB).
     
  3. The Java Scanner Class parses the underlying stream of data slowly, because of which it cannot provide fast I/O in Java.
     
  4. It is not synchronised. 
     
  5. The Scanner class is available only in JDK 1.5 or higher. 

Important Points About Java Scanner Class

  • Imports Required: To use the Scanner class, you need to import java.util.Scanner at the beginning of your program.
     
  • Resource Management: Always close the Scanner object using scanner.close() to free up resources, especially when reading from files or streams.
     
  • Default Delimiter: The default delimiter for the Scanner class is whitespace, but it can be changed using the useDelimiter() method.
     
  • Data Type Parsing: The class provides methods like nextInt(), nextDouble(), and nextLine() for reading specific data types, which helps to avoid type conversion errors.
     
  • Buffering: The Scanner class uses buffering for efficient reading, which can enhance performance when processing large amounts of input.

Frequently Asked Questions

How to Import the Scanner Class in Java?

To import the Scanner class in Java, you use the import keyword followed by the package name java.util and then the class name Scanner. For example:

import java.util.Scanner;

Is Scanner Class a Superclass in Java?

No, the Scanner class is not a superclass in Java. It is a part of the java.util package and is used for obtaining input of primitive types and strings from the user or a file. It does not serve as a superclass for other classes.

What is the next Method in Scanner Class?

The next() method in the Scanner class reads the next token from the input stream. It skips any leading whitespace and returns the next complete token as a String. This method is commonly used for reading strings or tokens from the input source.

How to take string input in Java using the scanner class?

To take string input using the Scanner class, you have to use the Scanner class method nextLine( ) as follows:

String name = sc.nextLine( );

Conclusion

We are well aware of the importance of taking inputs from the user in a program. 

Keeping that in mind, we learnt how to use the Scanner class in Java to take user inputs. In that process, we also briefly saw the concept of packages and classes in Java. We also learnt about the different Scanner class methods, which help us take user inputs, thereby increasing the usability of our code. 

Explore similar topics:

Live masterclass