Scanner Class

Scanner class, introduced with J2SE 5.0, is a very useful new class that can parse text for primitive types and substrings using regular expressions.
The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions.
Important points about Scanner:
  • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
  • A scanning operation may block waiting for input.
  • A Scanner is not safe for multithreaded use without external synchronization.
Uses:-
  1. it shows how you can read input from stdin using Java's Scanner class.
  2. it shows how you can use the Scanner class to type check the user's input.
  3. it shows you Java's Console class.
  4. Much easier than older versions of text-based input in Java.
  5. Getting Input from Keyboard (System.in)
    1. Java provides two ways to read data from Keyboard Using Scanner class of java.util package.
    2. Using BufferedReader class of java.io package.
    3. Importing a class .
    Java provides import keyword to import a class or all classes of a package. Syntax:-
    import packagename.classname;
    import packagename.*;
    Example:-
    import java.util.Scanner;
    import java.util.*;
    Creating object of a class
    Use new keyword to create object of a class along with constructor.
    Syntax 1:
    new constructor();
    Syntax 2:
    Classname referencename=new constructor();
    Example:-
    Scanner sc=new Scanner(System.in);
    Using Scanner class
    Scanner class provides built-in methods to read data from given input device.
    1. String next()
    2. int nextInt()
    3. double nextDouble()
    4. float nextFloat()