Scanner Input, Tokens and StringTokenizer (ISC Class 12 Computer Science)
Updated 17 October 2026 · Draft, not yet fact-checked
Scanner (java.util) reads tokens separated by whitespace from the keyboard: nextInt(), nextDouble(), next() and nextLine(). StringTokenizer (java.util) breaks a String into tokens using delimiters: countTokens(), hasMoreTokens() and nextToken(). Wrong input throws InputMismatchException; stream classes such as BufferedReader throw IOException.
Understand Scanner Input, Tokens and the StringTokenizer Class
Tokens and whitespace. An input stream is a sequence of characters. A token is a group of characters between delimiters. By default the delimiters are whitespace: space, tab and newline. So "12 7 hello" holds three tokens.
Scanner. Import it with import java.util.*; and create Scanner sc = new Scanner(System.in);. Methods: nextInt(), nextDouble(), next() (the next token), nextLine() (the rest of the current line, including spaces), hasNext() and hasNextInt(). nextInt and next skip leading whitespace and stop before the delimiter after the token; nextLine reads up to and consumes the newline.
The nextInt, nextLine trap. After nextInt() the newline typed after the number is still in the input. A following nextLine() returns the empty remainder of that line. Fix: call nextLine() once to clear it, or read numbers as lines and convert with Integer.parseInt.
Input exceptions. If the user types text where nextInt() expects a number, Java throws InputMismatchException (an unchecked exception from java.util); the bad token is not consumed. Streams such as BufferedReader and InputStreamReader (java.io) can throw IOException, a checked exception that must be caught or declared with throws IOException. Handle with try-catch.
StringTokenizer. StringTokenizer st = new StringTokenizer(str); uses whitespace delimiters; new StringTokenizer(str, delims) uses every character of delims as a separate delimiter; a third argument true returns the delimiters as tokens too. Methods: countTokens() (tokens still remaining), hasMoreTokens(), nextToken() (returns a String). Convert with Integer.parseInt(token) when a token is a number. nextToken() on an empty tokenizer throws NoSuchElementException.
Typical program pattern: read a line with nextLine(), make a StringTokenizer, store countTokens() before the loop (it falls as tokens are taken), then loop with while (st.hasMoreTokens()).
Class design and constructors are in the previous topic.
Scanner Input, Tokens and the StringTokenizer Class: key facts
- Scanner methods
- nextInt() reads an int
- nextDouble() reads a double
- next() reads one token
- nextLine() reads the rest of the line
- Package java.util.
- StringTokenizer methods
- countTokens()
- hasMoreTokens()
- nextToken()
- Constructors: (str), (str, delims), (str, delims, true)
- countTokens() reduces as tokens are taken.
- Input exceptions
InputMismatchException Scanner got the wrong kind of token IOException stream input or output failure NoSuchElementException no token left - IOException is checked and must be caught or declared.
- Delimiters
Default delimiters space, tab, newline Delimiter string each character is a delimiter Third argument true delimiters are returned as tokens - Consecutive delimiters produce no empty token.
How to answer Scanner Input, Tokens and the StringTokenizer Class questions
Use this routine for input-handling programs.
- 1Import java.util.* (and java.io.* if you use BufferedReader).
- 2Create the Scanner; read numbers with nextInt or nextDouble and text with next or nextLine.
- 3After a number and before a line of text, add a nextLine() call to consume the leftover newline.
- 4For a sentence, read one line, build a StringTokenizer, store countTokens() first, then loop with hasMoreTokens().
- 5Convert numeric tokens with Integer.parseInt or Double.parseDouble.
- 6Wrap risky input in try-catch for InputMismatchException or NumberFormatException when the question asks.
Scanner Input, Tokens and the StringTokenizer Class in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Splitting a data line from a sensor
Suppose a weather logger sends the line "12,5;7" with commas and semicolons between readings, and a program must add the readings.
What is the total, and how many tokens are read if the delimiters are "," and ";"?
Try it first, then show the solutionSolution
- Tokens are 12, 5 and 7: three tokens.
- The sum is 12 + 5 + 7 = 24.
Answer: 3 tokens; total 24.
Memory hook: Every character in the delimiter string splits.
Name after age
Suppose a form program reads the age with nextInt() and then the full name with nextLine().
Why does the name come out empty, and what is the fix?
Try it first, then show the solutionSolution
- nextInt leaves the newline typed after the age in the input.
- The next nextLine reads that empty rest of the line; one extra nextLine() before it clears it.
Answer: The name is empty because of the leftover newline; call nextLine() once to discard it.
Memory hook: Numbers leave the Enter key behind.
Tricks to remember Scanner Input, Tokens and the StringTokenizer Class
Short memory aids. Say each one aloud once, then use it on a question the same day.
next stops, nextLine eats the line
next() stops at whitespace; nextLine() runs to the end of the line.
Use it when: Choosing the right read method.
Count first
Take countTokens() before the loop, because it shrinks as tokens are used.
Use it when: Counting words in a sentence.
Each delimiter character counts
In (str, ",;") the comma and the semicolon are two separate delimiters.
Use it when: Tokenizer with several delimiters.
IO is checked
IOException must be caught or thrown; InputMismatchException need not be.
Use it when: Exception questions.
Scanner Input, Tokens and the StringTokenizer Class: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Package of Scanner · 1 mark · MCQBoard level
The Scanner class belongs to the package
(a) java.lang (b) java.io (c) java.util (d) java.awt
Try it first, then show the solutionSolution
- Scanner and StringTokenizer are both in java.util.
Answer: (c) java.util
Example 2: Tokenizer with two delimiters · 3 marks · Short answerHarder board level
Write the output:
StringTokenizer st = new StringTokenizer("12,5;7", ",;");
int n = st.countTokens();
int sum = 0;
while (st.hasMoreTokens())
sum += Integer.parseInt(st.nextToken());
System.out.println(n + " " + sum);Try it first, then show the solutionSolution
- Delimiters are the comma and the semicolon, so the tokens are "12", "5" and "7": n = 3. (1 mark)
- The loop converts and adds: 12, then 17, then 24. (1 mark)
- Output: 3 24. (1 mark)
Answer: 3 24
Example 3: The nextInt and nextLine trap · 3 marks · Short answerHarder board level
The user types 5, presses Enter, then types hello world and presses Enter. Write the output and a correction:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.nextLine();
System.out.println("[" + s + "]");Try it first, then show the solutionSolution
- nextInt reads 5 and leaves the newline in the input. (1 mark)
- nextLine returns the rest of that first line, which is empty, so the output is []. (1 mark)
- Correction: add one sc.nextLine(); before reading s, or read with sc.nextLine() and convert; then s = "hello world". (1 mark)
Answer: [] ; fix by adding an extra sc.nextLine() after nextInt()
Example 4: Word count and longest word · 4 marks · Short answerHarder board level
Trace this program when the user types: java is fun to learn
import java.util.*;
public class Words {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
int n = st.countTokens();
String longest = "";
while (st.hasMoreTokens()) {
String w = st.nextToken();
if (w.length() > longest.length())
longest = w;
}
System.out.println(n + " " + longest);
}
}Try it first, then show the solutionSolution
- Five tokens: java, is, fun, to, learn, so n = 5 before the loop. (1 mark)
- Lengths 4, 2, 3, 2, 5. longest becomes java (4); is, fun and to are not longer; learn (5) is longer. (2 marks)
- Output: 5 learn. (1 mark)
Answer: 5 learn
Example 5: Case: marks entry that crashes · 4 marks · Case-basedHOTS / competency
Suppose a teacher's program reads a mark with int m = sc.nextInt(); and the user types abc.
(i) Name the exception. (1 mark)
(ii) Write a try-catch that prints Invalid mark. (2 marks)
(iii) A student also reads lines with BufferedReader.readLine(). Which exception must main declare or catch? (1 mark)
Try it first, then show the solutionSolution
- (i) InputMismatchException.
- (ii)
try { int m = sc.nextInt(); System.out.println(m); } catch (InputMismatchException e) { System.out.println("Invalid mark"); } - (iii) IOException, so main is written as public static void main(String[] args) throws IOException, or the call is placed in a try-catch.
Answer: (i) InputMismatchException (ii) catch it and print Invalid mark (iii) IOException
Where students lose marks in Scanner Input, Tokens and the StringTokenizer Class
The slips examiners see most often, and what to write instead.
Mistake: Counting tokens after the loop
countTokens() returns the remaining tokens, which is 0 once the loop has finished.
Wrong working
while (st.hasMoreTokens()) { ... } n = st.countTokens();
Right working
n = st.countTokens(); while (st.hasMoreTokens()) { ... }
Do this: Store the count before using the tokens.
Usually costs: 1 mark
Mistake: Forgetting to convert a token
nextToken() returns a String, which cannot be added as a number.
Wrong working
sum += st.nextToken();
Right working
sum += Integer.parseInt(st.nextToken());
Do this: Use parseInt or parseDouble.
Usually costs: 1 mark
Mistake: No import
Scanner and StringTokenizer are not in java.lang, so the program does not compile.
Wrong working
Scanner sc = new Scanner(System.in); with no import
Right working
import java.util.*; before the class
Do this: Write the import line first.
Usually costs: 1 mark
Exam tips
- Write the import statement; examiners check it.
- Name the exception exactly: InputMismatchException or IOException.
- Store countTokens() in a variable before the while loop.
- Show the token list when tracing a tokenizer question.
- Close the answer with the exact printed text, including spaces.
Practice questions on Scanner Input, Tokens and the StringTokenizer Class
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which StringTokenizer method returns the number of tokens still to be read?
(a) length() (b) countTokens() (c) size() (d) tokens()Hint
It is named for the tokens.
Answer
(b) countTokens()
Q2 · 2 marks · Short answerBoard level
Distinguish between next() and nextLine() of the Scanner class.
Hint
Think of what stops each one.
Answer
next() returns the next token and stops at whitespace, so it cannot read a space inside the text. nextLine() returns everything up to the end of the line, including spaces, and consumes the newline.
Q3 · 3 marks · Short answerHarder board level
How many tokens does StringTokenizer give for the String "a+b-c" with (i) the default delimiters, (ii) delimiters "+-", (iii) delimiters "+-" with returnDelims true? List the tokens in (iii).
Hint
There is no whitespace in the String.
Answer
(i) 1 token, the whole String, because it has no whitespace. (ii) 3 tokens: a, b, c. (iii) 5 tokens: a, +, b, -, c.
Q4 · 3 marks · Short answerHarder board level
Write the output:
StringTokenizer st = new StringTokenizer("one two three"); String s = ""; while (st.hasMoreTokens()) s = st.nextToken().charAt(0) + s; System.out.println(s);Hint
Each new character goes in front of the old text.
Answer
Tokens: one, two, three. s = "o"; then "t" + "o" = "to"; then "t" + "to" = "tto". Output: tto
Q5 · 4 marks · Case-basedHOTS / competency
A program reads an integer age and then a full name using sc.nextInt() and sc.nextLine(). (i) State the fault in the output. (ii) Rewrite the three input lines so that both values are read correctly. (iii) Give one other way to avoid the fault.
Hint
The Enter key typed after the number.
Answer
(i) The name is empty because nextLine reads the leftover end of the age line. (ii) int age = sc.nextInt(); sc.nextLine(); String name = sc.nextLine(); (iii) Read the age with nextLine() and convert it using Integer.parseInt(), so no newline is left behind.
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.What are the default delimiters of StringTokenizer?Show answer
Space, tab, newline and similar whitespace characters.
2.What does nextToken() return?Show answer
The next token as a String.
3.What is thrown when nextInt() meets the text abc?Show answer
InputMismatchException.
4.Is IOException checked?Show answer
Yes, it must be caught or declared.
5.What does nextLine() return after nextInt()?Show answer
The empty remainder of the same line.
6.In which package is StringTokenizer?Show answer
java.util.
Scanner Input, Tokens and the StringTokenizer Class: frequently asked questions
What is a token in Java input?
A sequence of characters between delimiters; with the default delimiters it is a group of characters separated by whitespace.
Why does nextLine() skip input after nextInt()?
nextInt() does not consume the newline typed after the number, so the next nextLine() reads that empty remainder; call nextLine() once more to discard it.
What is the use of the StringTokenizer class?
It breaks a string into tokens at chosen delimiters, so words or numbers in a line can be counted and processed one by one.
Do I have to catch InputMismatchException?
No, it is unchecked, but catching it lets the program report bad input instead of crashing.