Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 824
donnyton Avatar asked Aug 08 '11 14:08

donnyton


People also ask

Why StringTokenizer is deprecated?

StringTokenizer is a legacy class (i.e. there is a better replacement out there), but it's not deprecated. Deprecation only happens when the class/method has some serious drawbacks.

Why we are using StringTokenizer?

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

What does StringTokenizer return?

A token is returned by taking a substring of the string that was used to create the StringTokenizer object. It provides the first step in the parsing process often called lexer or scanner. The String Tokenizer class allows an application to break strings into tokens. It implements the Enumeration interface.


2 Answers

  1. Java 10 String Tokenizer -- not deprecated
  2. Java 9 String Tokenizer -- not deprecated
  3. Java 8 String Tokenizer -- not deprecated
  4. Java 7 String Tokenizer -- not deprecated
  5. Java 6 String Tokenizer -- not deprecated
  6. Java 5 String Tokenizer -- not deprecated

If it is not marked as deprecated, it is not going away.

like image 200
nicholas.hauschild Avatar answered Oct 07 '22 22:10

nicholas.hauschild


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().

like image 41
Jason S Avatar answered Oct 07 '22 21:10

Jason S