0% found this document useful (0 votes)
12 views10 pages

Skip To Contentc

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Skip To Contentc

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Strings in Java
String class in Java
Java.lang.String class in Java | Set 2
Why Java Strings are Immutable?
StringBuffer class in Java
StringBuilder Class in Java with Examples
String vs StringBuilder vs StringBuffer in Java
StringTokenizer Class in Java
StringTokenizer Methods in Java with Examples | Set 2
StringJoiner Class in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
StringTokenizer Class in Java
Last Updated : 08 Jan, 2024
StringTokenizer class in Java is used to break a string into tokens. 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.

Java String Tokenization


The String Tokenizer class allows an application to break strings into tokens. It
implements the Enumeration interface. This class is used for parsing data. To use
the String Tokenizer class we have to specify an input string and a string that
contains delimiters. Delimiters are the characters that separate tokens. Each
character in the delimiter string is considered a valid delimiter. Default
delimiters are whitespaces, new lines, spaces, and tabs.

Illustration:

stringtokenizer

Constructors of StringToken
Let us consider ‘str’ as the string to be tokenized. In that case we have three
constructor cases as mentioned below:

Constructor

Description

StringTokenizer(String str)

Default delimiters like newline, space, tab, carriage return, and form feed.

StringTokenizer(String str, String delim)

delim is a set of delimiters that are used to tokenize the given string.

StringTokenizer(String str, String delim, boolean flag)

The first two parameters have the same meaning wherein The flag serves the
following purpose.

Cases of StringToken Constructors


1. If the flag 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 flag 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".
Examples of Java String Tokenizer Constructors

// Java Program to implement


// Java String Tokenizer Constructors
import java.util.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Constructor 1
System.out.println("Using Constructor 1 - ");

// Creating object of class inside main() method


StringTokenizer st1 = new StringTokenizer(
"Hello Geeks How are you", " ");

// Condition holds true till there is single token


// remaining using hasMoreTokens() method
while (st1.hasMoreTokens())
// Getting next tokens
System.out.println(st1.nextToken());

// Constructor 2
System.out.println("Using Constructor 2 - ");

// Again creating object of class inside main()


// method
StringTokenizer st2 = new StringTokenizer(
"JAVA : Code : String", " :");

// If tokens are present


while (st2.hasMoreTokens())

// Print all tokens


System.out.println(st2.nextToken());

// Constructor 3
System.out.println("Using Constructor 3 - ");

// Again creating object of class inside main()


// method
StringTokenizer st3 = new StringTokenizer(
"JAVA : Code : String", " :", true);

while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
Output
Using Constructor 1 -
Hello
Geeks
How
are
you
Using Constructor 2 -
JAVA
Code
String
Using Constructor 3 -
JAVA

Code

String

Methods Of StringTokenizer Class


Method Action Performed
countTokens() Returns the total number of tokens present
hasMoreToken() Tests if tokens are present for the StringTokenizer’s string
nextElement() Returns an Object rather than String
hasMoreElements() Returns the same value as hasMoreToken
nextToken() Returns the next token from the given StringTokenizer.
Example of Methods of StringTokenizer Class
Below is the implementation of Methods:

// Java Program to implement


//
import java.util.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Creating a StringTokenizer
StringTokenizer str = new StringTokenizer(
"Welcome to GeeksforGeeks");

StringTokenizer temp = new StringTokenizer("");


// countTokens Method
int count = str.countTokens();
System.out.println(count);

// hasMoreTokens Methods
System.out.println("Welcome to GeeksforGeeks: "+str.hasMoreTokens());
System.out.println("(Empty String) : "+temp.hasMoreTokens());

// nextElement() Method
System.out.println("\nTraversing the String:");

while(str.hasMoreTokens()){
System.out.println(str.nextElement());
}

}
}
Output
3
Welcome to GeeksforGeeks: true
(Empty String) : false

Traversing the String:


Welcome
to
GeeksforGeeks

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Mohit Gupta

88
Previous Article
String vs StringBuilder vs StringBuffer in Java
Next Article
StringTokenizer Methods in Java with Examples | Set 2
Read More
Down Arrow
Similar Reads
StringTokenizer countTokens() Method in Java with Examples
The countTokens() method of StringTokenizer class calculate the number of times
that this tokenizer's nextToken method can be called before the method generates
any further exception. Note: The current position is not advanced during the
process. Syntax: public int countTokens() Parameters: The method does not take any
parameters. Return Value: The
2 min read
StringTokenizer hasMoreElements() Method in Java with Examples
The hasMoreElements() method of StringTokenizer class also checks whether there are
any more tokens available with this StringTokenizer. It is similar to the
hasMoreTokens(). The method exists exclusively so that the Enumeration interface of
this class can be implemented. Syntax: public boolean hasMoreElements() Parameters:
The method does not take
2 min read
StringTokenizer hasMoreTokens() Method in Java with Examples
The hasMoreTokens() method of StringTokenizer class checks whether there are any
more tokens available with this StringTokenizer. Syntax: public boolean
hasMoreTokens() Parameters: The method does not take any parameters. Return Value:
The method returns boolean True if the availability of at least one more token is
found in the string after the cu
2 min read
StringTokenizer nextToken() Method in Java with Examples
The nextToken() method of StringTokenizer class is used to return the next token
one after another from this StringTokenizer. Syntax: public String nextToken()
Parameters: The method does not take any parameters. Return Value: The method
returns the next token present in the line of the string tokenizer. Below programs
illustrate the working of nex
1 min read
StringTokenizer nextElement() Method in Java with Examples
The nextElement() method of StringTokenizer class is also used to return the next
token one after another from this StringTokenizer. It is similar to the nextToken()
method, except that the return type is Object rather than the String. Syntax:
public Object nextElement() Parameters: The method does not take any parameters.
Return Value: The method
2 min read
Difference Between StringTokenizer and Split Method in Java
Legacy classes and interfaces are the classes and interfaces that formed the
Collection Framework in the earlier versions of Java and how now been restructured
or re-engineered. Splitting of String is basically breaking the string around
matches of the given regular expression. Strings can be split in many ways in java
but the 2 most common ways ar
3 min read
StringTokenizer Methods in Java with Examples | Set 2
StringTokenizer class in Java is used to break a string into tokens. One must go
through StringTokenizer class where concepts and constructors are discussed which
help in better understanding methods that are been discussed here below as follows:
Methods of StringTokenizer class are as follows:
hasMoreTokennextTokencountTokensnextElementhasMoreElem
4 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class
Class represent classes and interfaces in a running Java application. The primitive
Java types (boolean, byte, char, short, int, long, float, and double), and the
keyword void are also represented as Class objects. It has no public constructor.
Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This
method returns the Java language modifiers for this class or interface, encoded in
an integer. The modifiers consist of the Java Virtual Machine's constants for
public, protected, private, final, static, abstract and interface. These modifiers
are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and
java.sql.Date in many instances. Whenever the java application interacts with the
database, we should use these instead of java.util.Date. The reason is JDBC i.e.
java database connectivity uses these to identify SQL Date and Timestamp. Here let
us see the differences
7 min read
Article Tags :
Java
Java-Library
Java-Strings
Practice Tags :
Java
Java-Strings
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like