What is java.util.Scanner in Java?
Overview
There are different default packages available in Java to facilitate the programmer. The java.util is one such package that contains a collection of different classes and frameworks.
Scanner is a class available in the java.util package. It is used to take input from a user for any primitive datatype (int, float, string, and so on).
Syntax
Before using the Scanner class, we need to import it.
import java.util.Scanner;
We can then create an object of the Scanner class by using the following syntax:
Scanner sc= new Scanner(System.in);
We are using sc as an example here, but we can also use any other variable name instead.
Parameters
System.in: This represents the object of the input stream. If we want to read the input from a file, thenSystem.inis replaced by an object of thefileclass.
Example code
The example below shows how we can take input from a user using the Scanner class object.
import java.util.Scanner;class ScannerExample {public static void main(String args[]){Scanner sc = new Scanner(System.in);System.out.println("Enter your Roll number");int id = sc.nextInt();System.out.println("Enter your grade");char grade = sc.next().charAt(0);System.out.println("Roll Number :" + id);System.out.println("Grade :" + grade);}}
Code explanation
- Line 1: We import the
Scannerclass. - Line 4: We create the object
scof theScannerclass. - Lines 5–6: We take an integer input from the user.
- Lines 7–8: We take a character input from the user.
- Lines 9–10: We display the inputs entered by the user.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved