BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Scanner class with examples

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial, you will learn Java Scanner class and how to use it in java programs to get the user input. This is one of the important classes as it provides you various methods to capture different types of user entered data. In this guide, we will discuss java Scanner class methods as well as examples of some of the important methods of this class.

The Scanner class is present in the java.util package so be sure import this package when you are using this class.

Example 1: Read user input text using Scanner

This is the first example of Scanner class, let’s discuss everything in detail.
1. The first statement import java.util.Scanner; is mandatory when using Scanner class. Alternatively, You can also import Scanner like this: java.util.*, this will import all the classes present in the java.util package.
2. While creating an object of Scanner class, we passed the System.in in the Scanner class constructor. This is to read the data from standard input.
3. We have used the nextLine() method of Scanner as this method is used to read the line of text entered by the user.

import java.util.Scanner;
public class JavaExample {
  public static void main(String[] args) {

    // creating a scanner
    Scanner scan = new Scanner(System.in);

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

    // read user input and store it in a string variable
    String firstName = scan.nextLine();

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

    // read second input
    String lastName = scan.nextLine();

    // prints the user entered data
    System.out.println("Your Name is: "+firstName+" "+lastName);

    // close scanner
    scan.close();
  }
}

Output:
Java Scanner with examples

Java Scanner class methods

In the above example, we have seen the use of nextLine() method. There are several methods available in this class. Let’s list down some of the frequently used methods of Scanner class.

Method Description
nextInt() It reads an int value entered by the user
nextFloat() It reads a float value entered by the user
nextBoolean() It reads a boolean value entered by the user
nextLine() It reads a line of text entered by the user
next() This method reads a word entered by the user
hasNextLine() Checks if there is another line of text entered by the user
hasNextInt() Checks if there is another int value input by the user
reset() It resets the scanner
toString() It is used to get string representation of user input
nextByte() This method reads a byte value entered by the user
nextDouble() This method reads a double value entered by the user
nextShort() It reads a short value entered by the user
nextLong() It reads a long value entered by the user

Example 2: Java Scanner nextInt() method

Here, we are demonstrating the use of nextInt() method. This method reads the integer value entered by the user. We are using the nextInt() method twice to get two numbers from user and then we are printing the sum of entered numbers.

import java.util.Scanner;
public class JavaExample {
  public static void main(String[] args) {

    // creating a scanner
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter first number: ");

    // read user input and store it in an int variable
    int num1 = scan.nextInt();

    System.out.print("Enter second number: ");

    // read second input
    int num2 = scan.nextInt();

    // prints the sum of entered numbers
    System.out.print("Sum of entered numbers: "+(num1+num2));

    // close scanner
    scan.close();
  }
}

Output:
Java Scanner example

Example 3: Java Scanner next() method

The next() method is different from the nextLine() method. Where the nextLine() method is used to read the line of text, the next() method reads the word entered by the user. The next() method reads the input until a whitespace is encountered. It doesn’t read the user input after whitespace.

In the following example, user is asked to enter the full name, however the next() method captured only the first name as it stopped reading input as soon as it found a whitespace. We will revisit the same example next with nextLine() method to get the desired output.

import java.util.Scanner;
public class JavaExample {
  public static void main(String[] args) {

    // creating a scanner
    Scanner scan = new Scanner(System.in);

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

    // read the user input using next() method
    // This method only reads a word, which means
    // if there is a whitespace between words, the
    // first word is scanned and second skipped
    String name = scan.next();

    System.out.print("You name: "+name);

    // close scanner
    scan.close();
  }
}

Output:
Java Scanner example

Example 4: Java Scanner nextLine() method

Let’s revisit the same example. As you can see, using nextLine(), we can read the complete user input. This is because this method reads a complete line.

import java.util.Scanner;
public class JavaExample {
  public static void main(String[] args) {

    // creating a scanner
    Scanner scan = new Scanner(System.in);

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

    // The nextLine() method works different from
    // the next() method, unlike next(), it reads the
    // complete line
    String name = scan.nextLine();

    System.out.print("You name: "+name);

    // close scanner
    scan.close();
  }
}

Output:
Java Scanner example

Example 5: Java Scanner useDelimiter() Method

The userDelimiter() method is used to specify a delimiter character in the input. In the following example, we have specified ‘/’ as a delimiter. We are also using hasNext() method of Scanner class to read the input separated by the delimiter.

import java.util.Scanner;
public class JavaExample {
  public static void main(String args[]){
    // Initializing a Scanner object
    Scanner scan = new Scanner("BeginnersBook/Chaitanya/Website");

    //Initialize the delimiter in useDelimiter() method
    scan.useDelimiter("/");

    //printing the strings separated by delimiter
    while(scan.hasNext()){
      System.out.println(scan.next());
    }
    scan.close();
  }
}

Output:

BeginnersBook
Chaitanya
Website
❮ Java TutorialArray in Java ❯

Top Related Articles:

  1. Convert Comma Separated String to HashSet in Java
  2. Remove special characters from a String in Java
  3. Java Integer byteValue() Method
  4. Constructor Overloading in Java with examples
  5. Java int to double Conversion

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap