Scanner class in java

In previous post , we have see Console class in java. In this post, we will see usage of Scanner class.

In java, Scanner class is used to read the input from keyboard. Even though, there are numerous ways to read the keyboard input, Scanner is one of them.

The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values.The resulting tokens may then be converted into values of different types using the various next methods

It can parse primitive types and strings using regular expressions.It implements Iterator and closeable Interfaces.

Few Constructors Of scanner class: 

  1. Scanner(File source): Constructs a new Scanner that produces values scanned from the specified file.
  2. Scanner(File source, String charsetName): Constructs a new Scanner that produces values scanned from the specified file.
  3. Scanner(InputStream source): Constructs a new Scanner that produces values scanned from the specified input stream.
  4. Scanner(InputStream source, String charsetName): Constructs a new Scanner that produces values scanned from the specified input stream.
  5. Scanner(String source): Constructs a new Scanner that produces values scanned from the specified string.

Commonly used methods of Scanner class:

Methods Description
public String next() It returns the next token from the scanner.
public String nextLine() it moves 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.

Example of Scanner class:

Output:
Enter your Empid 1234
Enter your name ABC
Enter your Salary 10000
EmpID:1234 name:ABC Salary:10000.0
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
Console Class in java
What is Exception Handling in java?
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *