0

In my understanding the StringTokenizer divides the String in tokens which on printing produces same result as split function depending on the delimiter. For example, consider this code:

String str="This is a text."; StringTokenizer st=new StringTokenizer(str); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } 

And this:

String str="This is a text."; String st[]=str.split(" "); for(int i=0;i<st.length;i++) { System.out.println(st[i]); } 

In both the cases the output is:

This is a text. 

Then why should I use StringTokenizer when I can achieve same thing with split function?

4
  • Easy. You shouldn't use StringTokenizer. Its Javadoc claims it is obsolete. Commented Mar 2, 2020 at 4:41
  • One advantage of StringTokenizer is that it will return which characters it splits on. String.split() doesn't, it just eats the delimiters. Commented Mar 2, 2020 at 4:52
  • @Dawood I can't find "obsolete" in Java SE 8 docs. Commented Mar 2, 2020 at 4:57
  • 2
    @TestCase The documentation says: "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". That means the class is obsolete, even if the word "obsolete" isn't explicitly used. Commented Mar 2, 2020 at 5:19

2 Answers 2

0

Note the following in the documentation 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.

So the advice is: don't use it. It's there only to avoid breaking old code.

Sign up to request clarification or add additional context in comments.

Comments

0

Both does the same thing.

StringTokenizer is a legacy class that is retained for compatibility reasons. Its use is discouraged in new code. It is recommended to use the split method of String or the java.util.regex package instead.

From Java official docs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.