C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Scanner class and its methods in Java

In this article, we are going to learn about Scanner class in Java and its some of the important methods (methods of Scanner class) with example.

Scanner class

It is used to create an object which is used to read data from input stream (keyboard).

Scanner class is defined in java.util package. So, we need to import this packet first before using the methods of Scanner class.

Objects are references variables in Java.


Scanner (object)

Method of Constructor

Scanner object_name  = new Scanner(input_stream_reference);


Scanner input = new Scanner (System.in);

Here, System.in is the reference of input (keyboard).

Methods of Scanner class

Here, we are discussing some of the important methods of Scanner class, which are used to design a Java program with user input. The methods are:

1) int nextInt()

It is used to read an integer value from the keyboard.

2) int nextFloat()

It is used to read a float value from the keyboard.

3) long nextLong()

It is used to read a long value from the keyboard.

4) String next()

It is used to read string value from the keyboard.

Consider the example:

import java.util.*;

public class InputExample{
     public static void main(String []args){
        String name;
        int age;
        float weight;
        //creating object of Scanner class
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your name: ");
        name = input.next();
        System.out.print("Enter your age: ");
        age = input.nextInt();
        System.out.print("Enter your weight: ");
        weight = input.nextFloat();        
        System.out.println("Name: " + name + ", Age: "+ age + ", Weight: "+ weight);


Enter your name: Mike
Enter your age: 23
Enter your weight: 55.50
Name: Mike, Age: 23, Weight: 55.5

Read more java examples.