What Is A Scanner Class In Java?

What Is A Scanner Class In Java?
What Is A Scanner Class In Java?

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.

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 the Scanner Class?

It is a class used to take inputs from the user. It is present in the utility package in Java (java.util). To understand this better, let us get a clear picture of a package, a class, and objects. 

By definition, a package is a collection of similar classes, and an object is an instance of a class. A class also contains functions related to it. To understand this, let us consider a real-life example. 

Let us consider the example of different edible items and their categories like fruits, vegetables, drinks, fast food, and desserts. All of them can be viewed as a class of the package “edibles”, but they have different features (giving rise to other objects) and ways to grow or make them (different functions). The following diagram shows this pictorially.

Similarly, the Scanner class is a part of java.util package. The package also has many other classes (some of which are shown), as shown in the diagram below. 

To summarise what we have learned so far, it is a class in java.util package that is used to take user inputs. Now that we know what the Scanner class is and why we use it, you may be wondering, how do we use it? Let’s see that next.

blog banner 1

How to use the Scanner Class? 

1. How to import Scanner in Java?

As we already know, the Scanner class is present in java.util package. So, to use the Scanner class, we must first import it from its package as follows:

import java.util.Scanner

import java.util.Scanner meaning is, we are importing the Scanner class from java.util package, which is what we wanted to do. 

2. Create a Scanner object

After importing the Scanner class, our next step is to create a Scanner object. The general syntax to do that is as follows:

Scanner object_name = new Scanner(InputStream input);

OR

Scanner object_name = new Scanner(File file);

OR

Scanner object_name = new Scanner(String str);

Usually, the argument passed to the Scanner class is an input stream, System.in. So you may have seen the following line to create a scanner object (which is sc here):

Scanner sc = new Scanner(System.in);

Now that we have imported the Scanner class and created a scanner object, you may be curious about taking user inputs. But, before we go to that, we must know about Scanner class methods in Java.

Scanner Class Methods in Java

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

3. Reading the user input

Now that we have imported the scanner class, created a scanner object, and know about scanner class methods, we can finally read the user input as follows:

data_type variable_name = object_name.scanner_class_method;

For example, let us consider the input for an integer variable X using the Scanner nextInt method.

int X = sc.nextInt( );

So far, we have learned about the Scanner class and how to use it. Let us now see a complete code using the Java Scanner class. (Also read about the Command Line Arguments In Java to understand more about role of command link in Java scanner)

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

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:

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

If you are using Java for your problem solving, then it becomes essential to use the best method for I/O as Java is slow compared to languages like C++.

Can we make Java easier for competitions like ACM ICPC?

Yes, the article on Fast Input/Output Methods in Java discusses different fast I/O methods in Java best suited for competitive programming and will help you change your verdict from TLE to AC.

Frequently Asked Questions

What is the Scanner class in Java?

Scanner class in Java is a class in java.util package that is used to take inputs from the user in a code.

Give an example of a Scanner class in Java.

Scanner class is a class present in the utility package (java.util) in Java. It is used to take user inputs. For example:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print(“Enter your age: “);
int age = sc.nextInt();
System.out.println(“Age: “+age);
}
}
Output:
Enter your age: 21
Age: 21

How do you import the scanner class in Java?

The syntax to import the Scanner class in Java is import java.util.Scanner.

What does sc.nextLine( ) do?

“sc” is usually the name of the Scanner class object, and nextLine( ) is a Scanner class method. So, it takes a line of text (with spaces) as input from the user and stores it in a string variable.

What does the scanner method nextLine( ) do?

The Scanner method nextLine( ) takes a line of text (with spaces) as input from the user and stores it in a string variable.

What’s the difference between next () and nextLine () in a scanner?

next( ) reads the input as a character variable only till space, while nextLine( ) reads the input (including spaces) till the end of the line (\n), as a string.

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( );

Key Takeaways

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

Keeping that in mind, we learned 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 learned about the different Scanner class methods, which help us take user inputs, thereby increasing the usability of our code. 

Our discussion does not end here, though. There are various other input methods in Java and other essential techniques in Java for you to learn. 

If you haven’t heard about BufferReader in Java yet, Don’t forget to read the blog on BufferReader vs Scanner Class in Java. 

You can quench your thirst for knowledge by checking out other blogs on Java here.

In conclusion, regular practice will ultimately be fruitful. So, remember to use CodeStudio to practice the wide range of DSA questions typically posed in interview rounds.

This will help you acquire practical coding approaches and provide you with interview experiences from scholars in significant product-based companies.

By Neelakshi Lahiri