Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

input
java.util.scanner

What is java.util.Scanner in Java?

Educative Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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, then System.in is replaced by an object of the file class.

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);
}
}
Example to take roll number and grade from a user as input

Code explanation

  • Line 1: We import the Scanner class.
  • Line 4: We create the object sc of the Scanner class.
  • 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.

RELATED TAGS

input
java.util.scanner
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring