Java StringTokenizer Class
Last Updated :
10 Jan, 2025
StringTokenizer class in Java is used to break a string into tokens based on delimiters. A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.
- 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.
- It implements the
Enumeration
interface. - To perform Java String Tokenization, we need to specify an input string and a set of delimiters.
- A delimiter is a character or set of characters that separate tokens in the string.
Note: StringTokenizer
is a legacy class, and the split()
method is preferred for modern applications.
Example: Below is a simple example that explains the use of Java StringTokenizer
to split a space-separated string into tokens:
Java
// Demonstration of Java StringTokenizer
import java.util.StringTokenizer;
public class Geeks {
public static void main(String[] args) {
// Input string
String s = "Hello Geeks how are you";
// Create a StringTokenizer object
// with space as the delimiter
StringTokenizer st = new StringTokenizer(s, " ");
// Tokenize the string and print each token
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
OutputHello
Geeks
how
are
you
Explanation: In the above example, we have created a StringTokenizer object by passing the string and a space " " as the delimiter. The hasMoreTokens() method checks there are more tokens available to process or not. The nextToken() method get the next token (substring).
Below is the representation of the process, which we defined in the above example:
Constructors of StringTokenizer Class
The StringTokenizer
class provides three constructors to tokenize strings in different ways.
Constructors | Description |
---|
StringTokenizer(String str) | Creates a tokenizer for the specified string. Uses default delimiters (whitespace, tabs, etc.). |
---|
StringTokenizer(String str, String delim) | Creates a tokenizer for the specified string using the given delimiters. |
---|
StringTokenizer(String str, String delim, boolean returnDelims) | Creates a tokenizer for the specified string using the given delimiters and specifies whether the delimiters should be returned as tokens. |
---|
Note:
- Default Delimiters: When no delimiter is specified, whitespace is used.
- returnDelims: If true, the delimiters are treated as tokens themselves.
Below is a concise explanation of how each constructor works, along with a code example in the combined way.
Cases of StringTokenizer Constructors
1. If the returnDelims is false, delimiter characters serve to separate tokens.
Example:
Input: if string --> "hello geeks" and Delimiter is " ", then
Output: tokens are "hello" and "geeks".
2. If the returnDelims is true, delimiter characters are considered to be tokens.
Example:
Input: String --> is "hello geeks" and Delimiter is " ", then
Output: Tokens --> "hello", " " and "geeks".
3. Multiple delimiters can be chosen for a single string.
Example:
Syntax: StringTokenizer st1 = new StringTokenizer( "2+3-1*8/4", "+*-/");
Input: String --> is "2+3-1*8/4" and Delimiters are +,*,-,/
Output: Tokens --> "2","3","1","8","4".
Example:
Java
// Demonstration of String Tokenizer Constructors
import java.util.*;
class Geeks {
public static void main(String[] args) {
// Example with Constructor 1
System.out.println("Using StringTokenizer Constructor 1: ");
// Using StringTokenizer to split the string into
// tokens using space (" ") as the delimiter
StringTokenizer st1 = new StringTokenizer(
"Geeks fo Geeks", " ");
// Iterate through tokens while
// there are more tokens available
while (st1.hasMoreTokens())
// Getting and printing the next token
System.out.println(st1.nextToken());
// Example with Constructor 2
System.out.println("Using StringTokenizer Constructor 2: ");
// Using StringTokenizer to split the string
// using ":" as the delimiter
StringTokenizer st2 = new StringTokenizer(
"java : Code : String : Tokenizer", " :");
// Iterate through tokens and print them
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
// Example with Constructor 3
System.out.println("Using StringTokenizer Constructor 3: ");
// Using StringTokenizer with returnDelims = true
// to include delimiters as tokens
StringTokenizer st3 = new StringTokenizer(
"java : Code", " :", true);
// Iterate through tokens (including delimiters)
// and print them
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
OutputUsing StringTokenizer Constructor 1:
Geeks
fo
Geeks
Using StringTokenizer Constructor 2:
java
Code
String
Tokenizer
Using StringTokenizer Constructor 3:
java
:
Code
Methods Of StringTokenizer Class
Below are some commonly used methods of StringTokenizer class along with a combined code example demonstrating some of these methods.
Example:
Java
// Demonstration of StringTokenizer Methods
import java.util.*;
class Geeks {
public static void main(String[] args) {
// Creating a StringTokenizer
StringTokenizer st = new StringTokenizer(
"Welcome to GeeksforGeeks");
StringTokenizer st1 = new StringTokenizer("");
// countTokens Method
int c = st.countTokens();
System.out.println(c);
// hasMoreTokens Methods
System.out.println("Welcome to GeeksforGeeks: "+ st.hasMoreTokens());
System.out.println("(Empty String) : "+ st1.hasMoreTokens());
// nextElement() Method
System.out.println("\nTraversing the String:");
while(st.hasMoreTokens()){
System.out.println(st.nextElement());
}
}
}
Output3
Welcome to GeeksforGeeks: true
(Empty String) : false
Traversing the String:
Welcome
to
GeeksforGeeks
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Java Programs - Java Programming Examples
In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read