Java Scanner class

To make coding less, the Designers introduced java.util.Scanner (Scanner is not from package) in Java 5. Earlier to Java Scanner class, keyboard input was taken using DataInputStream and BufferedReader, both requiring extra code of parsing the user input. Java Scanner avoids parsing.
Example on Java Scanner taking Keyboard input
import java.util.Scanner;
public class KeyboardScanner
 public static void main(String args[])
   Scanner scan = new Scanner(;
					// start taking input
   System.out.println("Enter Your Name:");
   String name = scan.nextLine();

   System.out.println("Enter Your Age:");
   int age = scan.nextInt();
   System.out.println("Enter Your Salary:");
   double salary = scan.nextDouble();
					// now display
   System.out.println("Your Name is " + name);
   System.out.println("Your Age is " + age);
   System.out.println("Your Salary is Rs." + salary);

Java Scanner
Output screenshot on Java Scanner

nextLine(), nextInt() and nextDouble() reads, takes user input returns as a string, int and double which can be used straightaway in the coding for all arithmetic operations.

For another example where you can take name, age and salary in a single statement refer Keyboard Input – java.util.Scanner – No parsing

For more on Scanner coding refer Scanner – Checking for Tokens

1 thought on “Java Scanner class”

Leave a Comment

Your email address will not be published.