By WebNest Studio Engineering Team
Java - Core Tutorial
StringTokenizer Class in Java
StringTokenizer, found in java.util, is one of Java's oldest utility classes for breaking a string into smaller pieces called tokens, based on a set of delimiter characters. It predates Java's regular expression support and is considered a legacy class today — it is worth knowing for reading older codebases, but new code should generally prefer String.split().
Why it matters
StringTokenizer is a legacy class that you will still meet in older codebases, textbooks and exam questions. You need to be able to read it and to know how it differs from split() — in particular that it silently skips empty tokens — so that you can replace it safely when maintaining old code.
Basic Usage and Methods
You construct a StringTokenizer with the string to split and (optionally) a set of delimiter characters — if no delimiter is given, it defaults to whitespace (space, tab, newline). The class exposes a small, simple API for walking through the tokens one at a time.
hasMoreTokens()— returns true if at least one token remains to be read.nextToken()— returns the next token as a String and advances the internal position.countTokens()— returns the number of tokens remaining (without consuming them).
Why String.split() Is Preferred Today
String.split(regex), added later, is far more powerful because it accepts a full regular expression rather than a fixed set of delimiter characters, so it can split on patterns like "one or more spaces" or "a comma optionally followed by a space." It also returns a String array, which integrates naturally with modern Java code (streams, for-each loops, and so on), whereas StringTokenizer implements the older Enumeration-style iteration. For any new code you write, split() (or, for more complex parsing, the java.util.regex package) is the right tool; StringTokenizer is mainly useful today for recognizing it when reading legacy code.
Example
Splitting a comma-separated string into tokens
import java.util.StringTokenizer;
public class StringTokenizerDemo {
public static void main(String[] args) {
StringTokenizer tokenizer = new StringTokenizer("Java,Python,C++,Kotlin", ",");
System.out.println("Token count: " + tokenizer.countTokens());
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Token count: 4
Java
Python
C++
Kotlin
Common Mistakes
- Calling nextToken() without first checking hasMoreTokens(), which throws a NoSuchElementException once all tokens are consumed.
- Trying to pass a regular expression as the delimiter argument — StringTokenizer treats every character in the delimiter string as a literal character, not a pattern.
- Using StringTokenizer in new code out of habit when String.split() or Pattern/Matcher would be simpler and more capable.
- Assuming StringTokenizer preserves empty tokens between consecutive delimiters — it simply skips them, unlike split() with a limit argument.
Exercise
Use a StringTokenizer to print each word of a sentence on its own line, followed by the number of words.
Expected output: learn, java, with, webnest, then Words: 4
import java.util.StringTokenizer;
public class WordList {
public static void main(String[] args) {
String sentence = "learn java with webnest";
StringTokenizer tokens = new StringTokenizer(sentence);
// TODO: remember how many tokens there are, then print each one
}
}
Show hints
countTokens()returns how many tokens are left, so read it before the loop consumes them.- Loop while
hasMoreTokens()is true and read each one withnextToken().
Show solution
import java.util.StringTokenizer;
public class WordList {
public static void main(String[] args) {
String sentence = "learn java with webnest";
StringTokenizer tokens = new StringTokenizer(sentence);
int total = tokens.countTokens();
while (tokens.hasMoreTokens()) {
System.out.println(tokens.nextToken());
}
System.out.println("Words: " + total);
}
}
Quick quiz
1. What does a StringTokenizer split on when you do not specify a delimiter?
- A. Whitespace such as spaces, tabs and newlines
- B. Commas
- C. Every character
- D. Nothing
Show answer
A. The default delimiters are whitespace characters: space, tab, newline, carriage return and form feed.
2. How many tokens does new StringTokenizer("a,,b", ",") produce?
- A. 3
- B. 2
- C. 4
- D. 1
Show answer
B. StringTokenizer skips empty tokens, so it yields only "a" and "b". "a,,b".split(",") would give three elements, including an empty one.
3. Is StringTokenizer recommended for new code?
- A. Yes, it is the fastest option
- B. Only for multi-threaded code
- C. No, it is a legacy class; use split() or java.util.regex instead
- D. Only for reading files
Show answer
C. The Java documentation itself describes StringTokenizer as a legacy class kept for compatibility and recommends split() or the regex package.
Interview questions
What is the difference between StringTokenizer and String.split()?
Show answer
split() takes a regular expression and returns all the pieces at once in an array, keeping empty strings between adjacent delimiters. StringTokenizer takes a set of delimiter characters, hands out tokens one at a time, and skips empty tokens.
split() is the modern choice: it works with regex patterns, the result can be indexed and reused, and it does not hide missing fields.
Key Points to Remember
- StringTokenizer splits a string into tokens using a fixed set of delimiter characters.
- Core methods: hasMoreTokens(), nextToken(), and countTokens().
- It is a legacy class; String.split() (regex-based) is the modern, preferred approach for new code.
- StringTokenizer is still worth recognizing when reading or maintaining older Java codebases.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering