«Back to Home

Core Java

Topics

Scanner Class In Java

Scanner Class
 
The java.util.Scanner class is also used to read the input from the keyboard.
 
By default, Scanner class breaks the input into the tokens, using a delimiter that is whitespace.
 
Scanner class provides the various methods to read and parse various primitive values. It is generally used to parse the text for the string and primitive types, using regular expression. This class extends Object class and implements Iterator interface and Closeable interface.
 
A scanning operation may block waiting for the input and Scanner class is not safe for the multithreaded use without an external synchronization.
 
Methods of Scanner class

public String next()

This method is used to return the next token from the scanner.
 
public String nextLine()

This method is used to return the scanner position to the next line and returns the value as a string.
 
public byte nextByte()

It scans the next token as a byte.
 
public short nextShort()

It scans the next token as a short value.
 
public int nextInt()

It scans the next token as an int value.
 
public long nextLong()

It scans the next token as a long value.
 
public float nextFloat()

It scans the next token as a float value.
 
public double nextDouble()

It scans the next token as a double value.
 
Let’s see an example, given below.
 
Code
  1. import java.util.Scanner;  
  2. public class ScannerClass {  
  3.     public static void main(String args[]) {  
  4.         Scanner sc = new Scanner(System.in);  
  5.         System.out.println("Enter Student Name:");  
  6.         String name = sc.next();  
  7.         System.out.println("Enter Student Id:");  
  8.         double id = sc.nextDouble();  
  9.         System.out.println("Name:" + name + " Id:" + id);  
  10.         sc.close();  
  11.     }  
  12. }  
28

Output

29

In the example, shown above, we create a Scanner class that reads the int, string and double value as an input.
 
Let’s see another example, given below, Scanner class with delimiter.
 
Code
  1. import java.util.*;  
  2. public class ScannerClass {  
  3.     public static void main(String args[]) {  
  4.         String st = "10 methods 3 constructors 2 data members";  
  5.         Scanner sc = new Scanner(st).useDelimiter("\\s");  
  6.         System.out.println(sc.nextInt());  
  7.         System.out.println(sc.next());  
  8.         System.out.println(sc.nextInt());  
  9.         System.out.println(sc.next());  
  10.         sc.close();  
  11.     }  
  12. }  
30

Output

31

In the example, we can observe that scanner class breaks the input into tokens using a delimiter that is whitespace.
 
Summary

Thus, we learnt that java.util.Scanner class is also used to read the input from the keyboard and also learnt its important methods in Java.