Scanner Class in Java

Java Scanner is a simple text parser, it can parse a file, input stream or string into primitive and string tokens using regexp.

It breaks an input into the tokens using delimiter regular expression (whitespace by default Character#isWhitespace(char)).

Tokens can be converted into primitives (double, float, long, int, byte, short, boolean), number objects (BigDecimal, BigInteger) and String.

Scanner provides a bunch of methods to do that:

  • String next()
  • String nextLine()
  • double nextDouble()
  • float nextFloat()
  • int nextInt()
  • boolean nextBoolean()
  • BigDecimal nextBigDecimal()

and so on, no sense to mention all of available methods.

In general, Java Scanner API looks like an iterator pattern and consists of 4 steps:

  1. break input into tokens
  2. iterate through the tokens
  3. check hasNext() for each token
  4. retrieve its value if its exist

The most popular use cases:

Let’s take a deeper look at what is Scanner in Java program on practical examples.

Read Input From Console

When you’re starting learning Java one of the first questions is: “How to take input from a keyboard in Java?”.

You can do it using Scanner class.

For example, we want to enter numbers and show a sum at the end.

You can ask me: “How do you import scanner in Java?”. Easy –  import java.util.Scanner.

new Scanner( is waiting for user input, we’re iterating through each input value and putting this numbers into the list.

If a user enters “X” we stop a Java program.

Afterward, we’re calculating a sum of the numbers using Stream API and close a scanner.

Read Lines From a File

I already showed this example in my article “3 Ways How To Read File Line by Line in Java“, but I think it makes sense to duplicate it here as well.

A scanner parses a file and reads each line.

You can use InputStream or Path instead of  File class – it’s more or less the same.

Parse String By Delimiter

For example, you need to split a string by delimiter and parse int values.

To scan using delimiter we have to use  useDelimiter(pattern) method.

Since Java 9 you can get a stream of tokens and handle it in a functional way:

One more interesting method is  Stream<MatchResult> findAll(Pattern pattern).

It returns a stream of match results where you can extract groups.



There are 3 steps:

  1. Split a string by “|” character into tokens
  2. Parse each token by regexp into groups
  3. Extract groups

In this example, I have 3 groups – source token, number, and letter.


Java Scanner class is a really powerful instrument to parse a file, input stream or string.

It provides methods to convert tokens into primitives and some object types, sometimes it’s really useful.

Since Java 9 you can use Stream API and functional style of programming.

Any questions? Ask me.

1 Star2 Stars3 Stars4 Stars5 Stars
Scroll Up