Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.
Drawbacks of Scanner Class in Java
9.
Frequently Asked Questions
9.1.
How to Import the Scanner Class in Java?
9.2.
Is Scanner Class a Superclass in Java?
9.3.
What is the next Method in Scanner Class?
9.4.
How to take string input in Java using the scanner class?
10.
Conclusion
Last Updated: May 23, 2024
Easy

Scanner Class in Java

Author Rhythm Jain
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Getting to use a calculator in the exam was a thing many of us wished for, but why? Because it helps us with whatever tricky calculations we have to do. It has no limitations to the input and sometimes the function too.

OG Image

Now, imagine you had a calculator that can only add 1 and 2. Would it be of any use?

No, because we may need to perform different operations on different numbers, as per our needs. 

Therefore, a user must be able to give inputs to a device or software they are using. To incorporate this, the programs we write should take user inputs to suit the user’s needs. To do this, we use the scanner class in Java

This article will discuss the Scanner class in Java and how it is used to take user inputs.

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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:

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

Method

Description

nextInt( )

Takes integer input from the user

nextFloat( )

Takes floating-type 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);

}

}

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.

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. 

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:

Previous article
Singleton Class in java
Next article
Constructors
Live masterclass