Page 127 - CA_Blue( J )_Class9
P. 127
6.5 USING SCANNER CLASS
Scanner class was introduced in JDK 1.5. This class is used to input different types of values while executing a
program. Scanner class is defined in the “java.util” package.
To use the Scanner class we have to import the “java.util” package.
Dot Operator
import java.util.*;
Package Sub-package Name
We also have to create object of the Scanner class so that its method can be used.
Scanner Object Name
Scanner sc = new Scanner(System.in));
Class new Operator Constructor
The Scanner class in Java does use delimiters to split input into tokens. By default, whitespace (spaces, tabs,
newlines) is used as a delimiter. But to input different types of values for predefined data types, Java provides
various methods.
6.5.1 next() Method
It is used to read the next word (token) from the scanner object and return the token as a string value. For example,
to accept a word:
String w=sc.next();
6.5.2 nextLine() Method
It is used to read the complete line from the scanner object and returns line as a string value. For example, to
accept a line:
String s=sc.nextLine();
6.5.3 nextShort() Method
It is used to read a short type value from the scanner object and return token as a short value. For example, to
accept a short value:
short s= sc.nextShort();
6.5.4 nextInt() Method
It is used to read an integer value and returns token as an integer value. For example, to accept an integer value:
int n= sc.nextInt();
6.5.5 nextLong() Method
It is used to read a long integer value and returns token as a long integer value. For example, to accept a long
integer value:
long l= sc.nextLong();
Input in Java 125

