Class java.util.StringTokenizer

java.lang.Object

|

+----java.util.StringTokenizer

public class StringTokenizer

extends Object

implements Enumeration

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnTokens flag having the value true or false:

●If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.

●If the flag is true, delimiter characters are considered to be tokens. A token is either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

The following is one example of the use of the tokenizer. The code:

StringTokenizer st = new StringTokenizer("this is a test");

while (st.hasMoreTokens()) {

println(st.nextToken());

}

prints the following output:

this

is

a

test

Constructor

StringTokenizer(String)

Constructs a string tokenizer for the specified string.

StringTokenizer(String, String)

Constructs a string tokenizer for the specified string.

StringTokenizer(String, String, boolean)

Constructs a string tokenizer for the specified string.

Method

countTokens()

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

hasMoreElements()

Returns the same value as the hasMoreTokens method.

hasMoreTokens()

Tests if there are more tokens available from this tokenizer's string.

nextElement()

Returns the same value as the nextToken method, except that its declared return value is Object rather than String.

nextToken()

Returns the next token from this string tokenizer.

nextToken(String)

Returns the next token in this string tokenizer's string.

Constructor

StringTokenizer

public StringTokenizer(String str,

String delim,

boolean returnTokens)

Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens.

If the returnTokens flag is true, then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. If the flag is false, the delimiter characters are skipped and only serve as separators between tokens.

Parameters:

str - a string to be parsed.

delim - the delimiters.

returnTokens - flag indicating whether to return the delimiters as tokens.

StringTokenizer

public StringTokenizer(String str,

String delim)

Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens.

Parameters:

str - a string to be parsed.

delim - the delimiters.

StringTokenizer

public StringTokenizer(String str)

Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is "\t\n\r": the space character, the tab character, the newline character, and the carriage-return character.

Parameters:

str - a string to be parsed.

Methods

hasMoreTokens

public boolean hasMoreTokens()

Tests if there are more tokens available from this tokenizer's string.

Returns:

true if there are more tokens available from this tokenizer's string; false otherwise.

nextToken

public String nextToken()

Returns the next token from this string tokenizer.

Returns:

the next token from this string tokenizer.

Throws:NoSuchElementException

if there are no more tokens in this tokenizer's string.

nextToken

public String nextToken(String delim)

Returns the next token in this string tokenizer's string. The new delimiter set remains the default after this call.

Parameters:

delim - the new delimiters.

Returns:

the next token, after switching to the new delimiter set.

Throws:NoSuchElementException

if there are no more tokens in this tokenizer's string.

hasMoreElements

public boolean hasMoreElements()

Returns the same value as the hasMoreTokens method. It exists so that this class can implement the Enumeration interface.

Returns:

true if there are more tokens; false otherwise.

See Also:

Enumeration, hasMoreTokens

nextElement

public Object nextElement()

Returns the same value as the nextToken method, except that its declared return value is Object rather than String. It exists so that this class can implement the Enumeration interface.

Returns:

the next token in the string.

Throws:NoSuchElementException

if there are no more tokens in this tokenizer's string.

See Also:

Enumeration, nextToken

countTokens

public int countTokens()

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Returns:

the number of tokens remaining in the string using the current delimiter set.

See Also:

nextToken

Wrapper class

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

The wrapper classes in java servers two primary purposes.

●To provide mechanism to ‘wrap’ primitive values in an object so that primitives can do activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc. collection.

●To provide an assortment of utility functions for primitives like converting primitive types to and from string objects, converting to various bases like binary, octal or hexadecimal, or comparing various objects.

The following two statements illustrate the difference between a primitive data type and an object of a wrapper class:

int x = 25;
Integer y = new Integer(33);

The first statement declares an int variable named x and initializes it with the value 25. The second statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the object is assigned to the object variable y.

Below table lists wrapper classes in Java API with constructor details.

Primitive / Wrapper Class / Constructor Argument
boolean / Boolean / boolean or String
byte / Byte / byte or String
char / Character / char
int / Integer / int or String
float / Float / float, double or String
double / Double / double or String
long / Long / long or String
short / Short / short or String

Below is wrapper class hierarchy as per Java API

As explain in above table all wrapper classes (except Character) take String as argument constructor. Please note we might get NumberFormatException if we try to assign invalid argument in constructor. For example to create Integer object we can have following syntax.

Integer intObj = new Integer (25);
Integer intObj2 = new Integer ("25");

Here in we can provide any number as string argument but not the words etc. Below statement will throw run time exception (NumberFormatException)

Integer intObj3 = new Integer ("Two");

The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight wrapper classes.

The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper classes are found in the Java API documentation.

Method / Purpose
parseInt(s) / returns a signed decimal integer value equivalent to string s
toString(i) / returns a new String object representing the integer i
byteValue() / returns the value of this Integer as a byte
doubleValue() / returns the value of this Integer as an double
floatValue() / returns the value of this Integer as a float
intValue() / returns the value of this Integer as an int
shortValue() / returns the value of this Integer as a short
longValue() / returns the value of this Integer as a long
int compareTo(int i) / Compares the numerical value of the invoking object with that of i. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value.
static int compare(int num1, int num2) / Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2.
boolean equals(Object intObj) / Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it returns false.

Let’s see java program which explain few wrapper classes methods.

view plaincopy to clipboardprint?

  1. package WrapperIntro;
  2. public class WrapperDemo {
  3. public static void main (String args[]){
  4. Integer intObj1 = new Integer (25);
  5. Integer intObj2 = new Integer ("25");
  6. Integer intObj3= new Integer (35);
  7. //compareTo demo
  8. System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2));
  9. System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3));
  10. //Equals demo
  11. System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2));
  12. System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3));
  13. Float f1 = new Float("2.25f");
  14. Float f2 = new Float("20.43f");
  15. Float f3 = new Float(2.25f);
  16. System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2));
  17. System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));
  18. //Addition of Integer with Float
  19. Float f = intObj1.floatValue() + f1;
  20. System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );
  21. }
  22. }

Output:

valueOf (), toHexString(), toOctalString() and toBinaryString() Methods:

This is another approach to create wrapper objects. We can convert from binary or octal or hexadecimal before assigning value to wrapper object using two argument constructor. Below program explains the method in details.

view plaincopy to clipboardprint?

  1. package WrapperIntro;
  2. public class ValueOfDemo {
  3. public static void main(String[] args) {
  4. Integer intWrapper = Integer.valueOf("12345");
  5. //Converting from binary to decimal
  6. Integer intWrapper2 = Integer.valueOf("11011", 2);
  7. //Converting from hexadecimal to decimal
  8. Integer intWrapper3 = Integer.valueOf("D", 16);
  9. System.out.println("Value of intWrapper Object: "+ intWrapper);
  10. System.out.println("Value of intWrapper2 Object: "+ intWrapper2);
  11. System.out.println("Value of intWrapper3 Object: "+ intWrapper3);
  12. System.out.println("Hex value of intWrapper: " + Integer.toHexString(intWrapper));
  13. System.out.println("Binary Value of intWrapper2: "+ Integer.toBinaryString(intWrapper2));
  14. }
  15. }

Output:

Summary

●Each of primitive data types has dedicated class in java library.

●Wrapper class provides many methods while using collections like sorting, searching etc.

Nested Classes

In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class.

Syntax

The syntax to write a nested class is given below. Here the class Outer_Demo is the outer class and the class Inner_Demo is the nested class.

class Outer_Demo{

class Nested_Demo{

}

}

Nested classes are divided into two types:

Non-static nested classes: These are the non-static members of a class.

Static nested classes: These are the static members of a class.

Inner Classes (Non-static Nested Classes)

Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.

Inner classes are of three types depending on how and where you define them. They are:

●Inner Class

●Method-local Inner Classlass

●Anonymous Inner Class

Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.

Given below is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.

class Outer_Demo{

int num;

//inner class

private class Inner_Demo{

public void print(){

System.out.println("This is an
inner class");

}

}

//Accessing he inner class from the method
within

void display_Inner(){

Inner_Demo inner = new Inner_Demo();

inner.print();

}

}

public class My_class{

public static void main(String args[]){

//Instantiating the outer class

Outer_Demo outer = new Outer_Demo();

//Accessing the display_Inner() method.

outer.display_Inner();

}

}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method.

If you compile and execute the above program, you will get the following result.

This is an inner
class.

Accessing the Private Members

As mentioned earlier, inner classes are also used to access the private members of a class. Suppose a class is having private members to access them. Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class.

To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, you can instantiate the inner class as shown below.

Outer_Demo outer=new Outer_Demo();

Outer_Demo.Inner_Demo
inner=outer.new Inner_Demo();

The following program shows how to access the private members of a class using inner class.

class Outer_Demo {

//private variable of the outer class

private int num= 175;

//inner class

public class Inner_Demo{

public int getNum(){

System.out.println("This is the
getnum method of the inner class");

return num;

}

}

}

public class My_class2{

public static void main(String args[]){

//Instantiating the outer class

Outer_Demo outer=new Outer_Demo();

//Instantiating the inner class

Outer_Demo.Inner_Demo inner=outer.new
Inner_Demo();

System.out.println(inner.getNum());

}

}

If you compile and execute the above program, you will get the following result.

The value of num in
the class Test is: 175

Method-local Inner Class

In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method.

A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class.

public class Outerclass{

//instance method of the outer class

void my_Method(){

int num = 23;

//method-local inner class

class MethodInner_Demo{

public void print(){

System.out.println("This is
method inner class "+num);

}

}//end of inner class

//Accessing the inner class

MethodInner_Demo inner = new
MethodInner_Demo();

inner.print();

}

public static void main(String args[]){

Outerclass outer = new Outerclass();

outer.my_Method();

}

}

If you compile and execute the above program, you will get the following result.

This is method
inner class 23

Anonymous Inner Class

An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows:

AnonymousInner an_inner = new AnonymousInner(){

public void my_method(){

......

......

}

};

The following program shows how to override the method of a class using anonymous inner class.

abstract class AnonymousInner{

public abstract void mymethod();

}

public class Outer_class {

public static void main(String args[]){

AnonymousInner inner = new
AnonymousInner(){

public void mymethod(){

System.out.println("This is an
example of anonymous inner class");

}

};

inner.mymethod();

}

}

If you compile and execute the above program, you will get the following result.

This is an example
of anonymous inner class

In the same way, you can override the methods of the concrete class as well as the interface using an anonymous inner class.

Anonymous Inner Class as Argument

Generally if a method accepts an object of an interface, an abstract class, or a concrete class, then we can implement the interface, extend the abstract class, and pass the object to the method. If it is a class, then we can directly pass it to the method.

But in all the three cases, you can pass an anonymous inner class to the method. Here is the syntax of passing an anonymous inner class as a method argument:

obj.my_Method(new My_Class(){

public void Do(){

.....

.....

}

});

The following program shows how to pass an anonymous inner class as a method argument.

//interface

interface Message{

String greet();

}

public class My_class {

//method which accepts the object of
interface Message

public void displayMessage(Message m){

System.out.println(m.greet() +", This
is an example of anonymous inner class as an argument");

}

public static void main(String args[]){

//Instantiating the class

My_class obj = new My_class();

//Passing an anonymous inner class as an
argument

obj.displayMessage(new Message(){

public String greet(){

return "Hello";

}

});

}

}

If you compile and execute the above program, it gives you the following result.

Hello This is an
example of anonymous inner class as an argument

Static Nested Class

A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. The syntax of static nested class is as follows:

class MyOuter {

static class Nested_Demo{

}

}

Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class.