Search code examples
javastringsplitdeprecatedstringtokenizer

Why is StringTokenizer deprecated?


The Java documentation doesn't seem to mention anything about deprecation for StringTokenizer, yet I keep hearing about how it was deprecated long ago. Was it deprecated because it had bugs/errors, or is String.split() simply better to use overall?

I have some code that uses StringTokenizer and I am wondering if I should seriously be concerned about refactoring it to use String.split(), or whether the deprecation is purely a matter of convenience and my code is safe.


Solution

  • From the javadoc for StringTokenizer:

    StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

    If you look at String.split() and compare it to StringTokenizer, the relevant difference is that String.split() uses a regular expression, whereas StringTokenizer just uses verbatim split characters. So if I wanted to tokenize a string with more complex logic than single characters (e.g. split on \r\n), I can't use StringTokenizer but I can use String.split().