Page 356 - Computer science 868 Class 12
P. 356
2. Converts Primitive data types to String:
• <Wrapper class>.toString(primitive data type variable): This method is used to convert the primitive data type
to string str using the wrapper class.
Syntax: <primitive type> <variable> = <Wrapper class>.toString(primitive data type);
For example,
int v= 34;
String str=Integer.toString(v); // converts 34 to "34"
double d= 34.65;
String str=Double.toString(d); // converts 34.65 to "34.65"
Similarly, every data type can be converted to String and vice versa.
10.5 STRINGTOKENIZER CLASS
The StringTokenizer class breaks a sentence into tokens (sequence of characters except delimiters) or words. By default,
it takes space, \t, \n \r and \f as separators.
Syntax: StringTokenizer object = new StringTokenizer(String variable);
Example: StringTokenizer st = new StringTokenizer("Study Hard to get good marks");
We can also have other symbols as seperators apart from space. For doing so, we have to mention the type of delimiter.
Syntax: StringTokenizer object = new StringTokenizer(String variable, "delimiter");
Example: StringTokenizer st=new StringTokenizer("Study Hard, to get, good marks", "," );
The above class has six different functions.
• nextToken(): It is used to return the next token/word from the StringTokenizer object.
• hasMoreTokens(): It returns true if there is a token left in the StringTokenizer object else return false.
• countTokens(): It returns the total number of tokens in the object.
• hasMoreElements(): It is same as hasMoreTokens() and returns true if there is a token left in the StringTokenizer
object else return false.
• nextElement(): It is the same as nextToken() but its return type is Object.
Refer to the example given below.
Program 1 Write a program to count the number of words in a sentence and print them separately.
1 import java.util.*;
2 class Strtoken
3 {
4 public static void main(String args[])
5 {
6 StringTokenizer st = new StringTokenizer("I am studying-StringTokenizer"," ,-");
7 System.out.println("Number of Tokens " + st.countTokens());
8 System.out.println("The different words in the sentence are : ");
9 while (st.hasMoreTokens())
354354 Touchpad Computer Science-XII

