Title: Java StringTokenizer Example - Java Code Geeks
Open Graph Title: Java StringTokenizer Example - Java Code Geeks
Description: StringTokenizer class in Java is a class from java.util package. It allows us to break a string into tokens. Here, we show the use of String Tokenizer
Open Graph Description: StringTokenizer class in Java is a class from java.util package. It allows us to break a string into tokens. Here, we show the use of String Tokenizer
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-stringtokenizer-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/"},"author":{"name":"Katerina Zamani","@id":"https://examples.javacodegeeks.com/#/schema/person/94be714b6b9a82bb855c0d370c319673"},"headline":"Java StringTokenizer Example","datePublished":"2014-05-28T12:27:05+00:00","dateModified":"2021-04-07T11:14:41+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/"},"wordCount":677,"commentCount":0,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","articleSection":["StringTokenizer"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-stringtokenizer-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/","url":"https://examples.javacodegeeks.com/java-stringtokenizer-example/","name":"Java StringTokenizer Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2014-05-28T12:27:05+00:00","dateModified":"2021-04-07T11:14:41+00:00","description":"StringTokenizer class in Java is a class from java.util package. It allows us to break a string into tokens. Here, we show the use of String Tokenizer","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-stringtokenizer-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-stringtokenizer-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"util","item":"https://examples.javacodegeeks.com/category/java-development/core-java/util/"},{"@type":"ListItem","position":5,"name":"StringTokenizer","item":"https://examples.javacodegeeks.com/category/java-development/core-java/util/stringtokenizer/"},{"@type":"ListItem","position":6,"name":"Java StringTokenizer Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/94be714b6b9a82bb855c0d370c319673","name":"Katerina Zamani","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2013/11/Katerina-Zamani-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2013/11/Katerina-Zamani-96x96.jpg","caption":"Katerina Zamani"},"description":"Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.","sameAs":["https://www.javacodegeeks.com"],"url":"https://examples.javacodegeeks.com/author/katerina-zamani/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}},{"@type":"ListItem","position":4,"item":{"name":"util","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/util\/"}},{"@type":"ListItem","position":5,"item":{"name":"StringTokenizer","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/util\/stringtokenizer\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2014-05-28T15:27:05+03:00","datePublished":"2014-05-28T15:27:05+03:00","dateModified":"2021-04-07T14:14:41+03:00","headline":"Java StringTokenizer Example","name":"Java StringTokenizer Example","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/java-stringtokenizer-example\/","description":"StringTokenizer class in Java is a class from java.util package. It allows us to break a string into tokens. Here, we show the use of String Tokenizer class, as well as some of its basic operations. T","copyrightYear":"2014","articleSection":"StringTokenizer","articleBody":"\nStringTokenizer class in Java is a class from java.util package. It allows us to break a string into tokens. Here, we show the use of String Tokenizer class, as well as some of its basic operations.\n\n\n\nThe JDK version we use to compile the source code in this example is OpenJDK 13 and the IDE we use is Eclipse IDE 2020-03.\n\n\n\n1. Syntax of the constructors\n\n\n\nStringTokenizer provides three constructors listed in the table below. All of them construct a string tokenizer for the specified string. But the string tokenizer behaves in different ways based on the parameters provided to the constructor. Depending on our application, we can choose one of them.\n\n\n\nConstructorDescriptionStringTokenizer(String str)The default delimiters will be used and delimiter characters will not be returned as tokens. The default delimiter set includes: \" \\t\\n\\r\\f\" (the space character, the tab character, the newline character, the carriage-return character, and the form-feed character).StringTokenizer(String str, String delim)Custom delimiters can be specified by providing the delim parameter. Delimiter characters will not be returned as tokens. Note that it is valid to set delim as null when constructing a tokenizaer. But invoking other methods on the tokenizer constructed may result in a NullPointerException.StringTokenizer(String str, String delim, boolean returnDelims)Custom delimiters can be specified by providing the delim parameter. If the returnDelims flag is true, then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. Otherwise, the delimiter characters are skipped and will not be returned as tokens. Note that it is valid to set delim as null when constructing a tokenizer. But invoking other methods on the tokenizer constructed may result in a NullPointerException.Table. 1. StringTokenizer Constructors\n\n\n\n2. Methods of StringTokenizer\n\n\n\nThere are six public methods defined in StringTokenizer class as shown in the table below:\n\n\n\nMethodDescriptioncountTokens()Counts the number of tokens the tokenizer has.hasMoreElements()Same as the hasMoreTokens method.hasMoreTokens()Returns true if there are more tokens available from this tokenizer's string; otherwise returns false.nextElement()Same as the nextToken method, but returns Object rather than String.nextToken()Returns the next token from this tokenizer.nextToken(String delim)Returns the next token by using the delimiter specified.Table. 2. StringTokenizer Public Methods\n\n\n\n3. Example of StringTokenizer in Java\n\n\n\nLet's see how to use a StringTokenizer to break a string into tokens in the example below.\n\n\n\nimport java.util.StringTokenizer;\n\npublic class StringTokenizerExample {\n \/**\n * @param args\n *\/\n public static void main(String[] args) {\n String string1 = "It is cool to be a Java code geek!";\n System.out.printf("1. Breaks \\"%s\\" by space\\n", string1);\n\n \/\/ constructs a string tokenizer with default delimiters\n StringTokenizer tokenizer = new StringTokenizer(string1);\n \/\/ loop in order to take all tokens\n while (tokenizer.hasMoreTokens()) {\n \/\/ returns a string\n System.out.println(tokenizer.nextToken());\n }\n\n String string2 = "Java,C++,Basic,Python,Perl";\n System.out.printf("2. Breaks \\"%s\\" by comma\\n", string2);\n tokenizer = new StringTokenizer(string2, ",");\n System.out.println("The stokenizer includes " + tokenizer.countTokens() + " tokens.");\n while (tokenizer.hasMoreElements()) {\n \/\/ returns an object\n Object element = (String) tokenizer.nextElement();\n System.out.println(element.toString());\n }\n \n System.out.printf("3. Breaks \\"%s\\" by comma with delimiter returned\\n", string2);\n tokenizer = new StringTokenizer(string2, ",", true);\n System.out.println("The stokenizer includes " + tokenizer.countTokens() + " tokens.");\n while (tokenizer.hasMoreElements()) {\n \/\/ returns an object\n Object element = (String) tokenizer.nextElement();\n System.out.println(element.toString());\n }\n }\n}\n\n\n\nRun the example code above and you can see the output as below:\n\n\n\n1. Breaks \"It is cool to be a Java code geek!\" by space\nIt\nis\ncool\nto\nbe\na\nJava\ncode\ngeek!\n2. Breaks \"Java,C++,Basic,Python,Perl\" by comma\nThe stokenizer includes 5 tokens.\nJava\nC++\nBasic\nPython\nPerl\n3. Breaks \"Java,C++,Basic,Python,Perl\" by comma with delimiter returned\nThe stokenizer includes 9 tokens.\nJava\n,\nC++\n,\nBasic\n,\nPython\n,\nPerl\n\n\n\n\nAs you can see in the code above, we create three instances of StringTokenizer by using different constructors. In the first one, we use the default space delimiter, while in the second and the third one we choose the comma as the delimiter. In order to return all the tokens, we use a while loop where hasMoreTokens() or hasMoreElements() method is called which indicates whether there are available tokens. In addition, two operations exist (nextToken() and nextElement()) in order to return the value of the next token. The difference between them is that nextElement() method returns an Object instead of a String. Finally, countTokens() method returns the number of the tokens the tokenizer has. In the third tokenizer, we set the returnDelims flag to true to let it return the delimiter as token together with other tokens.\n\n\n\n4. StringTokenizer vs String.split()\n\n\n\nStringTokenizer was introduced since JDK 1.0. It is retained as a legacy class and mainly for compatibility reasons. So we'd better not to use it in our new code. Instead, the split method of String class introduced since JDK 1.4 provides similar functionality which is recommended. Also, for complex use cases, classes from java.util.regex package can be another option. \n\n\n\nIn the example below, we use String.split() method to break the same strings into tokens as we've done with StringTokenizer before.\n\n\n\npublic class StringSplitExample {\n \/**\n * @param args\n *\/\n public static void main(String[] args) {\n \/\/ split by the space character\n String string1 = "It is cool to be a Java code geek!";\n System.out.printf("1. Splits \\"%s\\" by space\\n", string1);\n String[] result = string1.split("\\\\s");\n for (int i = 0; i < result.length; i++) {\n System.out.println(result[i]);\n }\n\n \/\/ split by comma ","\n String string2 = "Java,C++,Basic,Python,Perl";\n System.out.printf("2. Splits \\"%s\\" by comma\\n", string2);\n result = string2.split(",");\n for (int i = 0; i < result.length; i++) {\n System.out.println(result[i]);\n }\n }\n}\n\n\n\nRun the example code above and you can see the output as below:\n\n\n\n1. Splits \"It is cool to be a Java code geek!\" by space\nIt\nis\ncool\nto\nbe\na\nJava\ncode\ngeek!\n2. Splits \"Java,C++,Basic,Python,Perl\" by comma\nJava\nC++\nBasic\nPython\nPerl\n\n\n\n\n5. Download the source code\n\n\n\nDownload\nYou can download the full source code of this example here: Java StringTokenizer Example\n\n\n\nLast updated on Jun 01st, 2020\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-stringtokenizer-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Katerina Zamani","url":"https:\/\/examples.javacodegeeks.com\/author\/katerina-zamani\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2014-05-28T12:27:05+00:00 |
| article:modified_time | 2021-04-07T11:14:41+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Katerina Zamani |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Katerina Zamani |
| twitter:label2 | Est. reading time |
| twitter:data2 | 5 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1