×

Difference between String Tokenizer and split Method in Java

Introduction

Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences

String Tokenizer

The String Tokenizer is an in-built class present in java. util package. The in-built class name is StringTokenizer. This class is used to break a given String into small parts. These small parts are known as Tokens.

The given String is broken into Tokens only with a certain recurring condition. Generally, the String is a group of characters. These groups of characters are separated by a certain character

Example

1.) He is playing cricket
The above string has been divided by a special character known as space ( )
2.) A=1; b=1; v=1; d=1;
The above statement is also a string but is been divided with the help of a special character semi colon ( ; )

These special characters used for dividing the String into parts are known as delimiters.

Here, the delimiter of the first statement is space and the delimiter of the second statement is a semi colon.

Methods in String Tokenizer

MethodUse
countTokens ( )The countTokens ( ) method is used to know the total number of tokens created from the specified String. The return data type for this method is Integer.
hasMoreTokens ( )The hasMoreTokens ( ) method is used to know whether we have any tokens further or not. If present, the value is true and in other cases false. The return data type for this method is Boolean.  
hasMoreElements ( )The method hasMoreElements ( ) works same as the method hasMoreTokens ( )
nextToken ( )The nextToken ( ) method is used to get the value of token. The values are printed only after checking the condition with the condition of hasMoreTokens ( ) The return data type for this method is String
nextElement ( )The method nextElement ( ) works same as the method nextToken ( ) The return data type for this method is the data type of the object created, except that its declared return value is Object rather than String

StringTokenizer Class Initialization

Syntax

1.) StringTokenizer object name = new StringTokenizer (String s1);
Here, the delimiters are taken directly as Space.
2.) StringTokenizer object name = new StringTokenizer (String s1, String delimiter1);
Here, the delimiters are specified by us.

Example Program

File Name: StrTok. java

// A program for String Tokenizer
import java. util. *;


public class StrTok
{
public static void main (String [ ] args) 
{

StringTokenizer st1 = new StringTokenizer ("He is Ben Stokes");
// No Delimiter Specified
System. out. println ("The total number of Tokens in String Tokenizer 1 are: "+st1. countTokens ());
System. out. println ("The token value of String Tokenizer 1 is: ");
while (st1. hasMoreTokens ())
{
    System. out. println (st1. nextToken ());
}

        System. out. println ("_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _\n");


StringTokenizer st2 = new StringTokenizer ("Vikram, Amar, Rolex, Dilli",", ");
// A delimiter of comma and space is given ", "
System. out. println ("The total number of Tokens in String Tokenizer 2 are: "+st2. countTokens ());
System. out. println ("The token value of String Tokenizer 2 is: ");


while (st2. hasMoreTokens ())
{
    System. out. println (st2. nextToken ());
}
System. out. println ("_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _\n");


StringTokenizer st3 = new StringTokenizer ("Program finished with exit code 0");
// No Delimiter Specified
System. out. println ("The total number of Tokens in String Tokenizer 3 are: "+st3. countTokens ());
System. out. println ("The token value of String Tokenizer 4 is: ");


while (st3. hasMoreElements ())
{
    System. out. println (st3. nextElement ());
}
    System. out. println ("_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _\n");



StringTokenizer st4 = new StringTokenizer ("Brand_ value_ is_ equal_ to_ perception" ,"_ ");

// Delimiter "_ " is specified
System. out. println ("The total number of Tokens in String Tokenizer 4 are: "+st4. countTokens ());
System. out. println ("The token value of String Tokenizer 4 is: ");


while (st4. hasMoreElements ())
{
    System. out. println (st4. nextElement ());
}
System. out. println ("_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _\n");





}
}

Output

The total number of Tokens in String Tokenizer 1 are: 4
The token value of String Tokenizer 1 is: 
He
is
Ben
Stokes
_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _


The total number of Tokens in String Tokenizer 2 are: 4
The token value of String Tokenizer 2 is: 
Vikram
Amar
Rolex
Dilli
_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _


The total number of Tokens in String Tokenizer 3 are: 6
The token value of String Tokenizer 4 is: 
Program
finished
with
exit
code
0
_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _


The total number of Tokens in String Tokenizer 4 are: 6
The token value of String Tokenizer 4 is: 
Brand
value
is
equal
to
perception
_  _  _  _  _  _  _   _  _  _  _  _  _  _  _  _

Split Method in Java

This is a method present in the java package named java. lang. This method is used to divide the elements into different entities. This is done for better viewing. The split method is an in-built method for Strings. So, this is used for better viewing of given or created String.

The elements after splitting are stored in String data typed array. The split method has two different syntaxes. Let us specify them first, and then explain them and their usage.

Syntax

1. String name. split ( String s1); // Here s1 indicates the delimiter not the String variable name
2. String name. split ( String s1, int limit);  // Here s1 indicates the delimiter not the String variable name

Let us now learn about the first syntax now

String Name. split (String s1) Usage

Here, s1 indicates the delimiters. All the delimiters are considered as a String. Usually, a String is divided into small parts with the help of some delimiters. We use split method which has specified delimiter divides the whole String into smaller Strings and we store them in separate String arrays.

Example Program

File Name: Split1. java

// A program for explaining the first syntax of split ( ) method
public class Split1
{
public static void main (String[ ] args) 
{
    String str = "Don't be afraid to give up the good to go for the great";
    
    String arr [ ] = str. split (" ");
    
        System. out. println ("The String after splitting is:");
    
    
    for (String i : arr)
    {
        System. out. println (i);
    }



}
}

Output

The String after splitting is:
Don't
be
afraid
to
give
up
the
good
to
go
for
the
great

Explanation

The given String is - > Don't be afraid to give up the good to go for the great

The words in String are separated from each other by a delimiter named space ( “ “ )

The split method uses this delimiter and stores the small sub String which occurs before the occurrence of delimiter into the created String Array.

Example: This is Page

Here, the space occurs immediately after This. So, This is stored into the created String Array.

Example Program 2

File Name: Split2. java

// A program for explaining the first syntax of split ( ) method
public class Split2
{
public static void main(String[] args) 
{
    String str = "Don't_ be_ afraid_ to_ give_ up_ the_ good_ to_ go_ for_ the_ great";
    
    String arr [] = str. split ("_ ");
    
        System. out. println ("The String after splitting is:");
    
    
    for (String i : arr)
    {
        System. out. println (i);
    }



}
}

Output

The String after splitting is:
Don't
be
afraid
to
give
up
the
good
to
go
for
the
great

String Name. split (String s1, int limit) Usage

Here, s1 indicates the delimiters. All the delimiters are considered as a String. Usually, a String is divided into small parts with the help of some delimiters. We use the split method which has a specified delimiter that divides the whole String into smaller Strings and we store them in separate String arrays.

All the splitting goes in the same way. But the number of splits occurring depends upon the value of limit. Based on the value of the limit, the number of sub strings created is dependent.

To be precise, the number of sub Strings created is numerically equal to the value of the limit specified.

Example Program

File Name: Split3. java

// A program for explaining the second syntax of split ( ) method
public class Split3
{
public static void main(String[] args) 
{
    String str = "Don't be afraid to give up the good to go for the great";
    
    String arr [] = str. split (" ", 7);
    
        System. out. println ("The String after splitting is:");
    
    
    for (String i : arr)
    {
        System. out. println (i);
    }



}
}

Output

The String after splitting is:
Don't
be
afraid
to
give
up
the good to go for the great

Explanation

The given String is - > Don't be afraid to give up the good to go for the great

The words in String are separated from each other by a delimiter named space ( “ “ )

The split method uses this delimiter and stores the small sub String which occurs before the occurrence of delimiter into the created String Array.

The limit value limits the total number of sub Strings created.

Here the limit value is seven ( 7 )

So, splitting will be done till the sixth delimiter is found.

After that splitting process is stopped and remaining chunk of String becomes a last sub String of the created String Array.

Example Program 2

File Name: Split4. java

// A program for explaining the sec syntax of split ( ) method
public class Mainond
{
public static void main(String[] args) 
{
    String str = "Don't be afraid to give up the good to go for the great";
    
    String arr [] = str. split (" ", 5);
    
   System. out. println ("The String after splitting is:");
      System. out. println ("The 5 SUB STRINGS are: ");


   
    
    
    for (String i : arr)
    {
        System. out. println (i);
    }



}
}

Output

The String after splitting is:
The 5 SUB STRINGS are: 
Don't
be
afraid
to
give up the good to go for the great

Differences between StringTokenizer and split Method

StringTokenizersplit ( ) method
It is a class present in java. util packageIt is a method present in java. lang package
It can only return a single Sub String at a timeThis method has the capability to return an array of Sub Strings at a single method call
It has constructorsNo constructors are available
The String Tokenizer have a few methods like countTokens ( ), hasMoreTokens ( ), nextToken ( ), hasMoreElements ( ), nextElement ( ) .split ( ) method itself is a method
The String Tokenizer do not have the concept of limiting the creation of Sub StringsThe split method has the concept of limiting the creation of Sub Strings
Hard Syntax to remember and not as flexible as spilt ( ) method for applicationEasy Syntax and can be applied easily
Less powerful when compared to the  split ( ) methodMore powerful when compared to the String Tokenizer concept
Very FastSlow when compared to the String Tokenizer
Empty Strings cannot be specifiedEmpty Strings can be specified

Related Topics

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.