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).
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.
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.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);}}
Scanner
class.sc
of the Scanner
class.Free Resources