Scanner class in Java

In this tutorial, we will learn about Scanner Class in Java. Scanner class in Java is used to get input from users as we use scanf() in C language. Scanner class is a predefined class in java which is present in java.util package. It means we have to import this package to use Scanner class in Program. Here we will learn how to use Scanner class and different methods of Scanner class.

Here I would like to start directly with an example which would so helpful to you to understand Scanner class.

// Import the Scanner class
import java.util.Scanner;  

class ScannerExample {
  public static void main(String[] args) {
    // Creating object of Scanner class
    Scanner obj = new Scanner(;  
    System.out.println("Enter First Number");
    int num1= obj.nextInt();  // Reading  user input

    System.out.println("Enter Second Number");
    int num2= obj.nextInt();  // Reading  user input
    System.out.println("Sum is: " + (num1+num2)); 

Here we will check available methods in Scanner class.

Method Description
nextBoolean() Read boolean input
nextByte() Read byte input
nextDouble() Read double input
nextFloat() Read float value
nextInt() Read int input
nextLine() Read string input
nextLong() Read long value
nextShort() Read short input
Spread the love
Scroll to Top