• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Introduction » Scanner Class in Java With Example
Next →
← Prev

Scanner Class in Java With Example

By Dinesh Thakur

In Java 1.5, a new class known as Scanner class was introduced to simplify the task of getting input from the user. The Scanner class is in java.util package which allows the user to read the data dynamically from the keyboard. It can be used to read a File on the disk. The Java Scanner class extends Object class is present in java.lang package and implements Iterator and Closeable interfaces.

The Java Scanner class that breaks down its input into tokens using any regular expression delimiter that is whitespace by default and it’s useful for parsing files also. Scanner class provides many methods to read and parse various primitive byte, short, int, float, double or even an object of String class. Java Scanner class commonly used to parse a string of text and primitive types using a regular expression. Before using a Scanner class, the program must import the package import java.util.*; OR  Java.util.Scanner;.

For example, java.util.Scanner specifies that Scanner is a class in the package util and util is a package in the package java. A Scanner class to create and obtain input from command window is as follows:

Scanner input = new Scanner(System.in);

As per the above syntax
• You can declare scanner type object say ‘input.’
• To create a Scanner object, the new keyword used.
•The Scanner class constructor, which takes an InputStream object (i.e., System.in) as a parameter. The System.in specifies the standard console keyboard input.

We’ll be covering the following topics in this tutorial:

  • How to construct a Java Scanner Class?
  • Advantage of using Scanner class in java
  • The disadvantage you may face with Scanner are

How to construct a Java Scanner Class?

We can create an instance of the Scanner class using one of the following constructors:

• Scanner(File source): It constructs a new Scanner that scans the specified file using the system’s default charset.

• Scanner(File source, String charsetName): It constructs a new Scanner that scans the specified file using the specified character set.

• Scanner(InputStream source): It constructs a new Scanner from a byte input stream using the system’s default charset.

• Scanner(InputStream source, String charsetName): It constructs a new Scanner from a byte input stream using the specified charset.

• Scanner(Readable source): It constructs a new Scanner from a character stream.

• Scanner(String source): It constructs a new Scanner from a String.

• Scanner(ReadableByteChannel source): constructs a Scanner that produces values scanned from the specified channel.

• Scanner(ReadableByteChannel source, String charsetName): constructs a Scanner that produces values scanned from the specified channel.

• Scanner(Path source): constructs a Scanner that produces values scanned from the specified file.

• Scanner(Path source, String charsetName): constructs a Scanner that produces values scanned from the specified file.

The various methods of the scanner class are as follows:

The nextShort, nextFloat, and nextLong methods in Scanner work similarly. Each of these methods (except nextLine) reads a set of consecutive characters until whitespace (such as a blank or a tab) encountered. The nextLine method reads all of the data that a user typed on a line before pressing the Enter key on a keyboard.

We can create a scanner that reads data from the console by using a System.in argument to the Scanner constructor:
Scanner scanner = new Scanner(System.in);
The value returned by a method can copy into a variable whose data type matches that of the returned value. For instance, the integer value that is returned by the nextInt method  copy into another variable called number1 using an assignment statement:
int number1 = scanner.nextlnt();
If the user enters a value that is different from the type expected (such as a floating-point number), a run-time error result.
The following statement reads a string from the console by using the next method and stores it in the variable named string1:
String string1 = scanner.next();
The variables number1 and string1 can be used as needed in the rest of the program.

We now make a small program that inputs two integers in Java and display result. In this program, we use the methods available in Scanner class to read data typed at the keyboard and place it into variables that we specify.

import java.util.*;
class InputDemo {
    public static void main (String args []) {
      int a,b;
      double pi;
      String name;
      Scanner s = new Scanner(System.in);
      System.out.printIn(“Enter thevalue of a & b”);
a = s.nextInt();
b = s.nextInt();
      System.out.printIn(“Enter the value of pi”);
pi = s.nextDouble();
      System.out.printIn(“Enter the your name”);
name = s.next();
      System.out.printIn(“The value of a = “+a);
      System.out.println(“The value of b = “+b);
      System.out.print1n(“The value of pi = “+pi);
      System.out.println(“Name = “+name );
   }
}

Advantage of using Scanner class in java

• Java Scanner class can do all that a BufferedReader class does with the same efficiency.
• Java Scanner is not thread safe, but BufferedReader is thread safe.
• Java Scanner class has various methods to manipulate input stream data.
• Java Scanner class tokenizes the underlying stream using a delimiter that is white space by default.
• The string manipulation in scanner class is entirely more comfortable as each word can be obtained as a token and handled separately.
• Java Scanner class can parse the underlying stream for string and primitive types like int, short, float, double, and long using regular expression.
• Java BufferedReader class can read only String but Scanner can read both String and primitive types.
• Java Scanner class use (1KB) little buffer size as comapre to BufferdReader class has a significantly large buffer (8KB), that means if you were reading Lengthy data from a file, then use BufferedReader but for short you use Scanner class.
• Java BufferedReader class is synchronized while Scanner class is not. Which means, you cannot share Scanner class between multiple threads, but you can share the BufferedReader class object.
• Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

The disadvantage you may face with Scanner are

• Java Scanner class is not synchronised.
• Java Scanner is not thread-safe.
• Java Scanner has little buffer memory (1KB).
• Java Scanner class can parse the underlying stream of data bit slower.
• Java Scanner class comes from JDK 1.5 higher.

You’ll also like:

  1. Write a java program to get the input through the keyboard using scanner class.
  2. Write a java program to calculate the simple and compound interest using Scanner class.
  3. Prime Number Program in Java Using Scanner Example.
  4. Write Data to a File Using Scanner in Java Example
  5. Java Class Example Code
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW