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?

Test Case
  • 3
  • 1
  • Easy. You _shouldn't_ use `StringTokenizer`. Its Javadoc claims it is obsolete. – Dawood ibn Kareem Mar 02 '20 at 04:41
  • One advantage of `StringTokenizer` is that it will return which characters it splits on. `String.split()` doesn't, it just eats the delimiters. – markspace Mar 02 '20 at 04:52
  • @Dawood I can't find "obsolete" in [Java SE 8 docs](https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html). – Test Case Mar 02 '20 at 04: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. – Slaw Mar 02 '20 at 05:19

2 Answers2

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.

sprinter
  • 24,103
  • 5
  • 40
  • 71
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.

Test Case
  • 3
  • 1
Chiran K.
  • 406
  • 2
  • 14