Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconScanner Class in Java: Types of Constructors & Methods, How to Use [With Examples]

Scanner Class in Java: Types of Constructors & Methods, How to Use [With Examples]

Last updated:
27th Jul, 2020
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Scanner Class in Java: Types of Constructors & Methods, How to Use [With Examples]

Anyone who works with the Java programming language is well aware of Scanner class in Java. And for aspiring Java Developers who don’t know what Scanner class is and how to use Scanner class in Java, this article is the perfect introduction to it. 

In this post, we’ll engage in a detailed discussion of Scanner class in Java, its different methods, and how they function. So, if you are looking forward to knowing more about Scanner class in Java, keep reading till the end!

Check out our free courses to get an edge over the competition.

What is the Scanner class in Java?

The Scanner class in Java is primarily used to obtain user input. The java.util package contains it. The Scanner class not only extends Object class, but it can also implement Iterator and Closeable interfaces. It fragments the user input into tokens using a delimiter, which is by default, whitespace.

Ads of upGrad blog

It is pretty easy to use the Scanner class – first, you create an object of the class and then use any of the available methods present in the Scanner class documentation.

Besides being one of the simplest ways of obtaining user input data, the Scanner class is extensively used to parse text for strings and primitive types by using a regular expression. For instance, you can use Scanner class to get input for different primitive types like int, long, double, byte, float, and short, to name a few. 

Check out upGrad’s Advanced Certification in Cloud Computing

You can declare Java Scanner class like so:

public final class Scanner  

          extends Object  

          implements Iterator<String> 

If you wish to obtain the instance of the Scanner class that reads user input, you have to pass the input stream (System.in) in the constructor of Scanner class, as follows:

Scanner in = new Scanner(“Hello upGrad”);

Explore our Popular Software Engineering Courses

Read: Top 6 Reasons Why Java Is So Popular With Developers

What are the different Scanner class constructors?

Here are the six commonly used Scanner class constructors:

  1. Scanner(File source) – It creates a new Scanner to generate values scanned from a particular file.
  2. Scanner(InputStream source) – It creates a new Scanner to produce values scanned from a specified input stream.
  3. Scanner(Readable source) – It creates a new Scanner to deliver values scanned from a specified source.
  4. Scanner(String source) – It creates a new Scanner to produce values scanned from a particular string.
  5. Scanner(ReadableByteChannel source) – It creates a new Scanner to produce values scanned from a specified channel.
  6. Scanner(Path source) – It creates a new Scanner to generate values scanned from a specified file.

Check out upGrad’s Advanced Certification in Blockchain

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

What are the different Scanner class methods?

Just like Scanner class constructors, there’s also a comprehensive suite of Scanner class methods, each serving a unique purpose. You can use the Scanner class methods for different data types. Below is a list of the most widely used Scanner class methods:

  1. void [close()] – This method is used to close the scanner.
  2. pattern [delimiter()] – This method helps to get the Pattern that is currently being used by the Scanner class to match delimiters.
  3. Stream<MatchResult> [findAll()] – It gives a stream of match results that match the specified pattern string.
  4. String [findInLine()] – It helps to find the next occurrence of a pattern created from a specified string. This method does not consider delimiters.
  5. String [nextLine()] – It is used to get the input string that was skipped of the Scanner object.
  6. IOException [ioException()] – This method helps to obtain the IOException last projected by the Scanner’s readable.
  7. Locale [locale()] – It fetches a Locale of the Scanner class.
  8. MatchResult [match()] – It offers the match result of the last scanning operation performed by the Scanner.
  9. BigDecimal [nextBigDecimal()] – This method is used to scan the next token of the input as a BigDecimal.
  10. BigInteger [nextBigInteger()] – This method scans the next token of the input as a BigInteger.
  11. byte [nextByte()] – It scans the next token of the user input as a byte value.
  12. double [nextDouble()] – It scans the next token of the user input as a double value.
  13. float [nextFloat()] – This method scans the next token of the input as a float value.
  14. int [nextInt()] – This method is used to scan the next token of the input as an Int value.
  15. boolean:
  • [hasNext()] – This method returns true if the Scanner has another token in the user input.
  • [hasNextBigDecimal()] – This method checks if the next token in the Scanner’s input can be interpreted as a BigDecimal by using the nextBigDecimal() method. 
  • [hasNextBoolean()] – It checks if the next token in the Scanner’s input can be interpreted as a Boolean using the nextBoolean() method.
  • [hasNextByte()] – It checks whether or not the next token in the Scanner’s input is interpretable as a Byte using the nextBigDecimal() method. 
  • [hasNextFloat()] – It checks whether or not the next token in the Scanner’s input is interpretable as a Float using the nextFloat() method.
  • [hasNextInt()] – It checks whether or not the next token in the Scanner’s input is interpretable as an Int using the nextInt() method.

Explore Our Software Development Free Courses

Check out: Java Developer Salary in India

How to use Scanner class in Java?

As we mentioned before, using the Scanner class in Java is quite easy. Below is an example demonstrating how to implement Scanner class using the nextLine() method:

import java.util.*;  

public class ScannerExample {  

public static void main(String args[]){  

          Scanner in = new Scanner(System.in);  

          System.out.print(“Enter your name: “);  

          String name = in.nextLine();  

          System.out.println(“Name is: ” + name);             

          in.close();             

          }  

}  

If you run this program, it will deliver the following output:

Enter your name: John Hanks

Name is: John Hanks

Ads of upGrad blog

Also Read: What is Type Casting in Java | Understanding Type Casting As a Beginner

In-Demand Software Development Skills

Wrapping up

This article covers the fundamentals of the Scanner class in Java. If you acquaint yourself with the Scanner class constructs and methods, with time and continual practice, you will master the craft of how to use Scanner class in Java programs.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1Why are pointers used in C++ and not in Java?

A pointer is a variable in languages like C and C++ that stores another variable's address value. They are not considered to be beginner-friendly for new programmers. Java keeps the simplicity of code in mind, and usage of concepts like pointers can increase complexity. Their utilization can also lead to potential errors. Also, there are security issues when we use pointers as the programmer can directly access the memory, and by mistake, there can be many repercussions. A distinct abstraction layer is added by not including the concept of pointers in Java. Also, the usage of pointers can make garbage collection error-prone and slow.

2How is the Java language different from the C++ language?

Both Java and C++ are object-oriented programming languages. Java was created by James Gosling, whereas Bjarne Stroustrup developed C++. Java is a platform-independent language and can be used on any OS using the byte code produced by JVM (Java Virtual Machine), whereas C++ is dependent on the platform. Java is portable to any operating system, whereas C++ is not portable. Java is a compiled and interpreted language, whereas C++ is just a compiled language. Java doesn't support multiple inheritance directly; you have to use interfaces to achieve it. On the other hand, you can directly achieve multiple inheritance in C++.

3How are abstract classes different from interfaces in the Java language?

An abstract class in Java cannot be instantiated or have any class objects, but it can be subclassed. An interface in Java specifies behavior that all the child classes must implement. In interfaces, only abstract methods can be used, whereas, in abstract classes, both abstract and non-abstract methods can co-exist. Only static and final variables can be used in interfaces, whereas abstract classes can also use non-static and non-final variables. Multiple inheritance is done by using interfaces which is not the case with abstract classes. An abstract class can easily implement an interface, whereas an interface cannot implement an abstract class.

Explore Free Courses

Suggested Blogs

Top 40 MySQL Interview Questions &#038; Answers For Beginners &#038; Experienced [2023]
118054
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

07 Nov 2023

Literals In Java: Types of Literals in Java [With Examples]
5958
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

29 Oct 2023

10 Interesting HTML Project Ideas &#038; Topics For Beginners [2023]
392833
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

04 Oct 2023

15 Exciting SQL Project Ideas &#038; Topics For Beginners [2023]
285278
Summary: In this Article, you will learn 15 exciting SQL project ideas & topics for beginners. Library Management System Centralized College Dat
Read More

by Rohan Vats

24 Sep 2023

17 Interesting Java Project Ideas &#038; Topics For Beginners 2023 [Latest]
35290
Summary: In this article, you will learn the 17 Interesting Java Project Ideas & Topics. Take a glimpse below. Airline reservation system Data v
Read More

by Rohan Vats

24 Sep 2023

9 Exciting Software Testing Projects &#038; Topics For Beginners [2023]
8308
Software testing might constitute 50% of a software development budget but it is viewed as a lethargic and unnecessary step by most students. Even edu
Read More

by Rohan Vats

21 Sep 2023

Top 10 Skills to Become a Full-Stack Developer in 2023
218239
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

21 Sep 2023

Java Free Online Course with Certification [2023]
57053
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers &#038; Experienced]
903223
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

20 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon