Scanner class is used to read input from keyboard. Scanner is class in
java.util package. Scanner class provides many methods to read and parse
primitive values. Scanner breaks the input into tokens using delimiter which is
by default whitespaces.
To read input from keyboard, we have to make an object of Scanner class
by passing predefined object called System.in.
Example:
Scanner sc = new Scanner(System.in);
Here sc is object of Scanner class and System.in represents
the standard input stream.
In java.util package, Scanner class extends Object class and implements Iterator and Closeable interfaces.
Methods in Scanner Class
There are many methods in Scanner class but most commonly used methods are:
1. next() is used to take single
word input
2. nextInt() is used to take integer
input
3. nextFloat() is used to take float
input
4. nextDouble() is used to take
double input
5. nextLong() is used to take long input
6. nextShort() is used to take
short input
7. nextLine() is used to take string
input
8. nextBoolean() is used to take boolean
input
next().charAt(0). is used to read a single
character.
Example of Java Scanner Class
import java.util.Scanner;
class ScannerExample{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
String s = sc.nextLine();
System.out.println("You have entered "+s);
System.out.print("\nEnter Integer Value : ");
int a = sc.nextInt();
System.out.println("You have entered "+a);
System.out.print("\nEnter Character Value : ");
char c = sc.next().charAt(0);
System.out.println("You have entered "+c);
}
}
Output:
Enter a String : Java
You have entered Java
Enter Integer Value : 10
You have entered 10
Enter Character Value : B
You have entered B