Scanner Class and StringTokenizer in Java (ISC Class 11 Computer Science)
Updated 17 October 2026 · Fact-checked
A stream is a flow of data between a program and a source or destination; System.in is the standard input stream and System.out the standard output stream. Input is read as tokens separated by whitespace. The Scanner class reads typed tokens with nextInt(), nextDouble(), next() and whole lines with nextLine(); the StringTokenizer class splits a string into tokens at given delimiters, with countTokens(), hasMoreTokens() and nextToken().
Understand Streams, Tokens, the Scanner Class and StringTokenizer
Streams and tokens. A *stream* is a sequence of data moving from a source (keyboard, file) to a program or from a program to a destination (screen, file). Data in a text stream are characters. A *token* is a group of characters separated from others by delimiters (by default whitespace: space, tab, newline).
Scanner class (import java.util.Scanner;)
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // reads the next token as int
double d = sc.nextDouble();
String w = sc.next(); // next token (a word)
String line = sc.nextLine(); // rest of the current line*Trap:* after nextInt() the newline typed by the user remains in the input; a following nextLine() returns the empty rest of that line. Use an extra sc.nextLine() to consume it. Other methods: hasNext(), hasNextInt(), nextBoolean(), nextLong(), next().charAt(0) for a char. If the token is not of the type requested, InputMismatchException is thrown.
StringTokenizer class (import java.util.StringTokenizer;)
StringTokenizer st = new StringTokenizer("to be or not"); // default delimiters: whitespace
StringTokenizer st2 = new StringTokenizer("12,45;7", ",;"); // user-defined delimitersMethods: countTokens() (number of remaining tokens), hasMoreTokens(), nextToken(). The delimiters themselves are not returned as tokens. nextToken() on an exhausted tokenizer throws NoSuchElementException.
Output. System.out.print() leaves the cursor on the same line; println() moves to the next line.
Scanner vs StringTokenizer. Scanner reads from a stream and converts types; StringTokenizer only splits a string into String tokens.
Streams, Tokens, the Scanner Class and StringTokenizer: key facts
- Scanner methods
- nextInt()
- nextDouble()
- next()
- nextLine()
- hasNext()
- Typed reading.
- Tokenizer methods
- countTokens()
- hasMoreTokens()
- nextToken()
- Splitting a string.
- Delimiter rule
- Default delimiters: space, tab, newline | Custom delimiters given as a String
- Not returned as tokens.
How to answer Streams, Tokens, the Scanner Class and StringTokenizer questions
Trace the input line by line, token by token.
- 1Write the input exactly as typed, with line breaks.
- 2For each Scanner call, consume the token or the rest of the line.
- 3Remember the leftover newline after nextInt().
- 4For StringTokenizer, list the tokens after removing delimiters.
Streams, Tokens, the Scanner Class and StringTokenizer 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.
Leftover newline
Suppose a program asks for a marks value using nextInt() and then asks for the student's name using nextLine(). The user types 85 and presses Enter, then types Riya.
What name does the program read?
Try it first, then show the solutionSolution
- nextInt() reads 85 but leaves the newline.
- nextLine() reads the empty rest of that first line, so name is an empty string.
Answer: An empty string; an extra nextLine() is needed after nextInt().
Memory hook: nextInt leaves the Enter behind.
Tricks to remember Streams, Tokens, the Scanner Class and StringTokenizer
Short memory aids. Say each one aloud once, then use it on a question the same day.
next reads a word, nextLine reads a line
next() stops at whitespace; nextLine() at the newline.
Use it when: Scanner.
Tokens exclude delimiters
Delimiters vanish.
Use it when: StringTokenizer.
Count then loop
countTokens() before nextToken().
Use it when: Avoiding exceptions.
Streams, Tokens, the Scanner Class and StringTokenizer: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Method choice · 1 mark · MCQBoard level
To read the whole line "Computer Science" typed by the user into a String variable using Scanner sc, you use:
(a) sc.next() (b) sc.nextLine() (c) sc.nextInt() (d) sc.hasNext()
Try it first, then show the solutionSolution
- next() would read only "Computer"; nextLine() reads the whole line.
Answer: (b) sc.nextLine()
Example 2: Tokenizer output · 3 marks · Short answerBoard level
Give the output:
StringTokenizer st = new StringTokenizer("12,45;7,90", ",;");
int c = st.countTokens();
int sum = 0;
while (st.hasMoreTokens())
sum += Integer.parseInt(st.nextToken());
System.out.println(c + " " + sum);(3 marks)
Try it first, then show the solutionSolution
- Delimiters are , and ;: tokens are 12, 45, 7, 90.
- countTokens() = 4.
- Sum = 12 + 45 + 7 + 90 = 154.
Answer: 4 154
Example 3: Leftover newline · 5 marks · Long answerHarder board level
A program runs: int a = sc.nextInt(); String s = sc.nextLine(); String t = sc.nextLine(); System.out.println(a + "|" + s + "|" + t); The input typed is two lines: 25 then Hello. Give the output and rewrite the code so that s reads "Hello". (5 marks)
Try it first, then show the solutionSolution
- nextInt() reads 25; the newline after 25 is left.
- s = nextLine() reads the empty rest of line 1: "".
- t = nextLine() reads the second line: "Hello".
- Output: 25||Hello. To read "Hello" into s, add sc.nextLine(); after nextInt() or read the number with Integer.parseInt(sc.nextLine()).
Answer: Output 25||Hello. Fix: int a = sc.nextInt(); sc.nextLine(); String s = sc.nextLine();
Example 4: Mixed input · 5 marks · Long answerHarder board level
The input is: 7 2.5 Java rocks. Write a code segment using Scanner to read the int, the double, the word and the rest of the line, and state the values read and the result of n * d. (5 marks)
Try it first, then show the solutionSolution
- n = nextInt() = 7; d = nextDouble() = 2.5; w = next() = "Java"; rest = nextLine() = " rocks" (with a leading space).
- n * d = 7 x 2.5 = 17.5.
Answer: n = 7, d = 2.5, w = "Java", rest = " rocks"; n * d = 17.5.
Example 5: Counting words with a tokenizer · 5 marks · Long answerHOTS / competency
Write a code segment that reads a sentence and prints the number of words and the longest word using StringTokenizer. Trace it for "learn java every day" and say what changes if the delimiter "," is also used for "a,b c". (5 marks)
Try it first, then show the solutionSolution
- Create the tokenizer; n = countTokens(); loop over tokens tracking the longest.
- "learn java every day": 4 words; lengths 5, 4, 5, 3; the first longest word is "learn" (if we update only on a strictly greater length).
- With ",", "a,b c" is split into three tokens: a, b, c; without "," it would be two tokens: "a,b" and "c".
Answer: 4 words; the longest word is learn (first of equal length); with "," added as a delimiter, "a,b c" gives 3 tokens.
Where students lose marks in Streams, Tokens, the Scanner Class and StringTokenizer
The slips examiners see most often, and what to write instead.
Mistake: Using nextLine() directly after nextInt()
Leftover newline.
Wrong working
int a = sc.nextInt(); String s = sc.nextLine();
Right working
Add sc.nextLine(); between them
Do this: Consume the newline.
Usually costs: 2 marks.
Mistake: Forgetting the import
Slipping.
Wrong working
Scanner without import java.util.Scanner;
Right working
import java.util.*;
Do this: Write the import.
Usually costs: 1 mark.
Mistake: Counting delimiters as tokens
Misreading.
Wrong working
12,45;7,90 has 7 tokens
Right working
4 tokens
Do this: Delimiters are removed.
Usually costs: 1-2 marks.
Exam tips
- Mention import statements.
- Show the input and where each call stops.
- Use countTokens() before looping over tokens.
Practice questions on Streams, Tokens, the Scanner Class and StringTokenizer
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 class is used to split a string into tokens?
(a) Scanner (b) StringTokenizer (c) Math (d) CharacterHint
Name says it.
Answer
(b) StringTokenizer
Q2 · 2 marks · Short answerBoard level
A user types Neha Sharma and presses Enter. What does String x = sc.next(); store, and what would String y = sc.nextLine(); have stored instead? (2 marks)
Hint
Whitespace vs newline.
Answer
x = "Neha" (stops at the space); y = "Neha Sharma" (the whole line).
Q3 · 4 marks · Short answerHarder board level
Give the output: StringTokenizer s = new StringTokenizer("this is, a test", ", "); System.out.println(s.countTokens()); while (s.hasMoreTokens()) System.out.print(s.nextToken().length() + " "); Also state the count for "10-20+30-40*2" with delimiters "-+*". (4 marks)
Hint
Delimiters are comma and space.
Answer
Tokens: this, is, a, test: countTokens() = 4. Output: 4 on the first line, then 4 2 1 4 on the next. For "10-20+30-40*2" the tokens are 10, 20, 30, 40, 2: count 5.
Q4 · 5 marks · Long answerHarder board level
Write a program fragment that reads 5 integers separated by spaces in one line using Scanner and prints their sum and average. State the output for the input 10 20 30 40 50. (5 marks)
Hint
Loop with nextInt().
Answer
int s = 0; for (int i = 0; i < 5; i++) s += sc.nextInt(); System.out.println(s + " " + (double) s / 5); Output: 150 30.0
Q5 · 4 marks · Short answerHOTS / competency
A program uses nextInt() for the number of students, then in a loop uses nextLine() to read each name. It reads the first name as an empty string. Explain the cause, give two ways to fix it and the effect on the number of names read for n = 3. (4 marks)
Hint
Leftover newline.
Answer
The newline after the number is left in the stream, so the first nextLine() returns "". Fix: call sc.nextLine() once after nextInt(), or read the number with Integer.parseInt(sc.nextLine()). With the bug, 3 calls give 1 empty and 2 real names (the third name is never read).
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.Standard input stream?Show answer
System.in.
2.Scanner method for an int?Show answer
nextInt().
3.StringTokenizer count method?Show answer
countTokens().
4.Default delimiter?Show answer
Whitespace.
5.Wrong type token throws?Show answer
InputMismatchException.
Streams, Tokens, the Scanner Class and StringTokenizer: frequently asked questions
Is Scanner in java.util?
Yes.
Can Scanner read from a file?
Yes, with a File object.
Does nextToken() return delimiters?
No.
What is a token?
A group of characters between delimiters.