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

Here, 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.out.print("Enter your name: ");
        name =;
        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.



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.