StringTokenizer in Java – Splitting Strings into Tokens
java.util.StringTokenizer breaks a string into tokens separated by delimiter characters. It has been part of Java since version 1.0 and is still found in older code and competitive programming. The Javadoc describes it as a legacy class kept for compatibility and recommends String.split() or the java.util.regex package for new code.
This tutorial covers its constructors and methods, custom delimiters, returning delimiters as tokens, how it differs from split(), and modern alternatives.
1. Constructors and Methods
| Constructor / method | Description |
|---|---|
StringTokenizer(String str) | Default delimiters: space, \t, \n, \r, \f |
StringTokenizer(String str, String delim) | Each character of delim is a delimiter |
StringTokenizer(String str, String delim, boolean returnDelims) | If true, delimiters are returned as tokens |
boolean hasMoreTokens() | Whether more tokens remain |
String nextToken() | The next token; NoSuchElementException if none |
String nextToken(String delim) | Switch delimiters, then return the next token |
int countTokens() | Tokens remaining |
hasMoreElements() / nextElement() | The same, via the Enumeration interface |
2. Using StringTokenizer
import java.util.StringTokenizer;
public class TokenizerBasics {
public static void main(String[] args) {
// 1. Default delimiters: space, tab, newline, carriage return, form feed
StringTokenizer st = new StringTokenizer("Java is\tsimple and\npowerful");
System.out.println("countTokens() = " + st.countTokens());
while (st.hasMoreTokens()) System.out.println(" " + st.nextToken());
// 2. Custom delimiters: every character in the string is a delimiter
StringTokenizer csv = new StringTokenizer("Asha,29;Pune|Developer", ",;|");
StringBuilder sb = new StringBuilder();
while (csv.hasMoreTokens()) sb.append('[').append(csv.nextToken()).append(']');
System.out.println(sb);
// 3. returnDelims = true: delimiters are returned as tokens too
StringTokenizer expr = new StringTokenizer("12+7*3-4", "+-*", true);
StringBuilder parts = new StringBuilder();
while (expr.hasMoreTokens()) parts.append(expr.nextToken()).append(' ');
System.out.println("expression tokens: " + parts.toString().trim());
}
}
countTokens() = 5 Java is simple and powerful [Asha][29][Pune][Developer] expression tokens: 12 + 7 * 3 - 4
- Consecutive delimiters are treated as one: the three spaces after "Java" produced no empty tokens.
- The delimiter string is a set of single characters, not a pattern:
",;|"splits on any of them. - With
returnDelims = true, operators in an expression are kept, which is handy for simple parsers.
3. StringTokenizer vs split()
import java.util.Arrays;
import java.util.StringTokenizer;
public class TokenizerVsSplit {
public static void main(String[] args) {
String line = "Asha,,Pune,";
// StringTokenizer skips empty tokens
StringTokenizer st = new StringTokenizer(line, ",");
StringBuilder tokens = new StringBuilder();
while (st.hasMoreTokens()) tokens.append('[').append(st.nextToken()).append(']');
System.out.println("StringTokenizer : " + tokens);
// split keeps empty tokens in the middle (and drops trailing ones by default)
System.out.println("split(\",\") : " + Arrays.toString(line.split(",")));
System.out.println("split(\",\", -1) : " + Arrays.toString(line.split(",", -1)));
// split uses regular expressions; StringTokenizer uses single characters
System.out.println("split(\"\\\\s*,\\\\s*\"): " + Arrays.toString("a , b,c ,d".split("\\s*,\\s*")));
}
}
StringTokenizer : [Asha][Pune]
split(",") : [Asha, , Pune]
split(",", -1) : [Asha, , Pune, ]
split("\\s*,\\s*"): [a, b, c, d]
| Aspect | StringTokenizer | String.split() |
|---|---|---|
| Delimiter | Set of characters | Regular expression |
| Empty tokens | Skipped | Kept (trailing ones dropped unless limit is negative) |
| Result | Iterated one by one | String[] array |
| Return delimiters | Optional | No (use regex lookarounds) |
| Status | Legacy | Recommended |
Skipping empty tokens is a real difference for data such as CSV, where an empty field matters: StringTokenizer silently loses it.
4. Modern Alternatives
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ModernAlternatives {
public static void main(String[] args) {
String data = "java spring kafka docker";
// Pattern + stream
List<String> words = Pattern.compile("\\s+").splitAsStream(data).toList();
System.out.println("splitAsStream : " + words);
// Scanner with typed tokens
try (Scanner sc = new Scanner("10 20 x 30")) {
int sum = 0;
while (sc.hasNext()) {
if (sc.hasNextInt()) sum += sc.nextInt(); else sc.next();
}
System.out.println("Scanner sum : " + sum);
}
}
}
splitAsStream : [java, spring, kafka, docker] Scanner sum : 60
String.split(regex)for simple splitting into an array.Pattern.splitAsStreamorString.lines()when a stream is convenient.Scannerfor reading typed tokens (nextInt,nextDouble) from strings, files or input.- A proper CSV library (such as OpenCSV or Apache Commons CSV) for real CSV with quotes and escapes.
5. Summary
StringTokenizersplits a string into tokens using a set of delimiter characters.- Iterate with
hasMoreTokens()andnextToken();countTokens()gives the remaining count. - It skips empty tokens and can optionally return delimiters.
- It is a legacy class: prefer
split(), regex orScannerin new code.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is StringTokenizer in Java?
A class in java.util that splits a string into tokens using delimiter characters.
Q2. Is StringTokenizer deprecated?
Not formally deprecated, but the Javadoc calls it a legacy class and discourages its use in new code.
Q3. What are the default delimiters?
Space, tab (\t), newline (\n), carriage return (\r) and form feed (\f).
Q4. Can StringTokenizer use multiple delimiters?
Yes. Every character in the delimiter string is a separate delimiter, for example ",;|".
Q5. Can I use a multi-character delimiter like "::"?
No. Each character is treated individually. Use split("::") for multi-character separators.
Q6. Does StringTokenizer return empty tokens?
No. Consecutive delimiters are treated as one, so empty tokens are skipped.
Q7. What does countTokens() return?
The number of tokens remaining from the current position, not the original total.
Q8. What happens if I call nextToken() with no tokens left?
It throws NoSuchElementException. Check hasMoreTokens() first.
Q9. What is the returnDelims parameter?
When true, delimiter characters are returned as tokens of length one, which helps when parsing expressions.
Q10. Which is faster, StringTokenizer or split()?
StringTokenizer can be slightly faster because it avoids regex, and split has a fast path for single-character delimiters. The difference rarely matters.
Q11. Does StringTokenizer support regular expressions?
No. Use String.split, Pattern or Scanner for regex-based splitting.
Q12. Which interface does StringTokenizer implement?
Enumeration<Object>, so it also offers hasMoreElements() and nextElement().
Q13. Can I change delimiters while tokenizing?
Yes. nextToken(String delim) switches to new delimiters for that and subsequent calls.
Q14. Is StringTokenizer thread-safe?
No. It keeps a current position, so one instance should be used by one thread.
Q15. Why is StringTokenizer used in competitive programming?
Combined with BufferedReader, it reads large inputs faster than Scanner.
Q16. How do I convert tokens into a list?
Loop with hasMoreTokens and add each nextToken() to a list, or use Arrays.asList(s.split(...)) instead.
Q17. Can StringTokenizer handle quoted CSV fields?
No. It has no notion of quotes or escapes. Use a CSV library for real CSV data.
Q18. What is the difference between StringTokenizer and Scanner?
Scanner supports regex delimiters, typed parsing (nextInt) and many input sources; StringTokenizer only returns string tokens from a string.
Q19. What is the opposite of StringTokenizer?
Joining tokens back together, done with StringJoiner, String.join or Collectors.joining.
Q20. Which package contains StringTokenizer?
java.util.