Scanner Class in Java

Prev Tutorial Next Tutorial

Java Scanner Class in Java

Scanner is one of the predefined class which is used for reading the data dynamically from the keyboard.

Import Scanner class

Import Scanner Class in Java


Constructor of Scanner Class


This constructor create an object of Scanner class by talking an object of InputStream class. An object of InputStream class is called in which is created as a static data member in the System class.

Syntax of Scanner Class in Java

Scanner  sc=new  Scanner(;

Here the object 'in' is use the control of keyboard

scanner class in java scanner class in java

Instance methods of Scanner Class

1public byte nextByte()Used for read byte value
2public short nextShort()Used for read short value
3public int nextInt()Used for read integer value
4public long nextLong()Used for read numeric value
5public float nextLong()Used for read numeric value
6public double nextDouble()Used for read double value
7public char nextChar()Used for read character
8public boolean nextBoolean()Used for read boolean value
9public String nextLine()Used for reading any kind of data in the form of String data.

Method 1 to 8 are used for reading fundamental values from the keyboard. Method 9 (public String nextLine() ) is used for reading any kind of data in the form of String data.

For Remember all above methods

From method 1 to 8 combindly we represent as public xxx nextxxx(). Here xxx represents any fundamental data type. These methods are used for reading the fundamental data from keyboard.

Accept two values dynamically from the keyboard and compute sum.

Example of Scanner Class in Java

import java.util.Scanner
public class ScannerDemo
public static void main(String args[])
Scanner  s=new  Scanner(;
System.out.println("Enter first no= ");
int num1=s.nextInt();
System.out.println("Enter second no= ");
int num2=s.nextInt();
System.out.println("Sum of no is= "+(num1+num2));


Enter first no=4
Enter second no=5
Sum of no is=9

Program which is accept two number as a string and compute their sum.


import java.util.Scanner;
class Dataread 
public static void main(String[] args) 
Scanner s=new Scanner(;
System.out.println("Enter first number: ");
String s1=s.nextLine();
System.out.println("Enter second number: ");
String s2=s.nextLine();
int res=Integer.parseInt(s1) + Integer.parseInt(s2);
System.out.println("Sum= "+res);


Enter first number: 5
Enter second number: 6
Sum= 11

Prev Tutorial Next Tutorial

Download Projects


FREE Online Google Play APK Downloader

Buy APP Installs, Buy 100% Genuine Installs