Java Basics Unit 5
Java Basics Unit 5
Java Basics Unit 5
This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
2 The List Interface
This extends Collection and an instance of List stores an ordered
collection of elements.
3 The Set
This extends Collection to handle sets, which must contain unique
elements.
4 The SortedSet
This extends Set to handle sorted sets.
5 The Map
This maps unique keys to values.
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in an ascending order.
8 The Enumeration
This is legacy interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects. This legacy
interface has been superceded by Iterator.
1 AbstractCollection
Implements most of the Collection interface.
2 AbstractList
Extends AbstractCollection and implements most of the List interface.
3 AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than
random access of its elements.
4 LinkedList
Implements a linked list by extending AbstractSequentialList.
5 ArrayList
Implements a dynamic array by extending AbstractList.
6 AbstractSet
Extends AbstractCollection and implements most of the Set interface.
7 HashSet
Extends AbstractSet for use with a hash table.
8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.
9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.
10 AbstractMap
Implements most of the Map interface.
11 HashMap
Extends AbstractMap to use a hash table.
12 TreeMap
Extends AbstractMap to use a tree.
13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing
documents.
1 Vector
The List interface extends Collection and declares the behavior of a collection that
stores a sequence of elements.
• Elements can be inserted or accessed by their position in the list, using a
zero-based index.
• A list may contain duplicate elements.
• In addition to the methods defined by Collection, List defines some of its
own, which are summarized in the following table.
• Several of the list methods will throw an UnsupportedOperationException if
the collection cannot be modified, and a ClassCastException is generated
when one object is incompatible with another.
Sr.No. Method & Description
1
void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in the index. Any pre-
existing elements at or beyond the point of insertion are shifted up. Thus,
no elements are overwritten.
2
boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in the
index. Any pre-existing elements at or beyond the point of insertion are
shifted up. Thus, no elements are overwritten. Returns true if the invoking
list changes and returns false otherwise.
3
Object get(int index)
Returns the object stored at the specified index within the invoking
collection.
4
int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not
an element of the list, .1 is returned.
5
int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not
an element of the list, .1 is returned.
6
ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
7
ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
8
Object remove(int index)
Removes the element at position index from the invoking list and returns
the deleted element. The resulting list is compacted. That is, the indexes of
subsequent elements are decremented by one.
9
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
10
List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list.
Elements in the returned list are also referenced by the invoking object.
Example
The above interface has been implemented in various classes like ArrayList or
LinkedList, etc.
Following is the example to explain few methods from various class implementation
of the above collection methods –
importjava.util.*;
publicclassCollectionsDemo{
publicstaticvoidmain(String[]args){
List a1 =newArrayList();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t"+ a1);
List l1 =newLinkedList();
l1.add("Zara");
l1.add("Mahnaz");
l1.add("Ayan");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t"+ l1);
}
}
Output
ArrayList Elements
[Zara, Mahnaz, Ayan]
LinkedList Elements
[Zara, Mahnaz, Ayan]
Java - The Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects.
The methods declared by Enumeration are summarized in the following table −
Sr.No. Method & Description
1
boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to
extract, and false when all the elements have been enumerated.
2
Object nextElement( )
This returns the next object in the enumeration as a generic Object
reference.
Example
Following is an example showing usage of Enumeration.
importjava.util.Vector;
importjava.util.Enumeration;
publicclassEnumerationTester{
publicstaticvoidmain(Stringargs[]){
Enumeration days;
VectordayNames=newVector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days =dayNames.elements();
while(days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Java - The ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.
• Standard Java arrays are of a fixed length.
Following is the list of the constructors provided by the ArrayList class.
Sr.No. Constructor & Description
1
ArrayList( )
This constructor builds an empty array list.
2
ArrayList(Collection c)
This constructor builds an array list that is initialized with the elements of the
collection c.
3
ArrayList(int capacity)
This constructor builds an array list that has the specified initial capacity.
The capacity is the size of the underlying array that is used to store the
elements. The capacity grows automatically as elements are added to an
array list.
Apart from the methods inherited from its parent classes, ArrayList defines the
following methods −
Sr.No. Method & Description
1
void add(int index, Object element)
Inserts the specified element at the specified position index in this list.
Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >size()).
2
boolean add(Object o)
Appends the specified element to the end of this list.
3
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list,
in the order that they are returned by the specified collection's iterator.
Throws NullPointerException, if the specified collection is null.
4
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at
the specified position. Throws NullPointerException if the specified
collection is null.
5
void clear()
Removes all of the elements from this list.
6
Object clone()
Returns a shallow copy of this ArrayList.
7
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns
true if and only if this list contains at least one element e such that (o==null
? e==null : o.equals(e)).
8
void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that
it can hold at least the number of elements specified by the minimum
capacity argument.
9
Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0
|| index >= size()).
10
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element,
or -1 if the List does not contain this element.
11
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element,
or -1 if the list does not contain this element.
12
Object remove(int index)
Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if the index out is of range (index < 0 || index
>= size()).
13
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.
14
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified
element. Throws IndexOutOfBoundsException if the specified index is out of
range (index < 0 || index >= size()).
15
int size()
Returns the number of elements in this list.
16
Object[] toArray()
Returns an array containing all of the elements in this list in the correct
order. Throws NullPointerException if the specified array is null.
17
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct
order; the runtime type of the returned array is that of the specified array.
18
void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
Example
The following program illustrates several of the methods supported by ArrayList −
importjava.util.*;
public class ArrayListDemo{
Output
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Java - The LinkedList Class
1
LinkedList( )
This constructor builds an empty linked list.
2
LinkedList(Collection c)
This constructor builds a linked list that is initialized with the elements of the
collection c.
Apart from the methods inherited from its parent classes, LinkedList defines
following methods −
1
void add(int index, Object element)
Inserts the specified element at the specified position index in this list.
Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >size()).
2
boolean add(Object o)
Appends the specified element to the end of this list.
3
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list,
in the order that they are returned by the specified collection's iterator.
Throws NullPointerException if the specified collection is null.
4
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at
the specified position. Throws NullPointerException if the specified
collection is null.
5
void addFirst(Object o)
Inserts the given element at the beginning of this list.
6
void addLast(Object o)
Appends the given element to the end of this list.
7
void clear()
Removes all of the elements from this list.
8
Object clone()
Returns a shallow copy of this LinkedList.
9
boolean contains(Object o)
Returns true if this list contains the specified element. More formally,
returns true if and only if this list contains at least one element e such that
(o==null ? e==null : o.equals(e)).
10
Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).
11
Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if
this list is empty.
12
Object getLast()
Returns the last element in this list. Throws NoSuchElementException if
this list is empty.
13
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element,
or -1 if the list does not contain this element.
14
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element,
or -1 if the list does not contain this element.
15
ListIteratorlistIterator(int index)
Returns a list-iterator of the elements in this list (in proper sequence),
starting at the specified position in the list. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).
16
Object remove(int index)
Removes the element at the specified position in this list. Throws
NoSuchElementException if this list is empty.
17
boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).
18
Object removeFirst()
Removes and returns the first element from this list. Throws
NoSuchElementException if this list is empty.
19
Object removeLast()
Removes and returns the last element from this list. Throws
NoSuchElementException if this list is empty.
20
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified
element. Throws IndexOutOfBoundsException if the specified index is out
of range (index < 0 || index >= size()).
21
int size()
Returns the number of elements in this list.
22
Object[] toArray()
Returns an array containing all of the elements in this list in the correct
order. Throws NullPointerException if the specified array is null.
23
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct
order; the runtime type of the returned array is that of the specified array.
Example
The following program illustrates several of the methods supported by LinkedList −
Import java.util.*;
Public class LinkedListDemo{
Output
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
Java - The Vector Class
1
Vector( )
This constructor creates a default vector, which has an initial size of 10.
2
Vector(int size)
This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size.
3
Vector(int size, int incr)
This constructor creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time that a vector is resized upward.
4
Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.
Apart from the methods inherited from its parent classes, Vector defines the
following methods −
1
void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
2
boolean add(Object o)
Appends the specified element to the end of this Vector.
3
Boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this
Vector, in the order that they are returned by the specified Collection's
Iterator.
4
Boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into this Vector at
the specified position.
5
void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size
by one.
6
int capacity()
Returns the current capacity of this vector.
7
void clear()
Removes all of the elements from this vector.
8
Object clone()
Returns a clone of this vector.
9
boolean contains(Object elem)
Tests if the specified object is a component in this vector.
10
booleancontainsAll(Collection c)
Returns true if this vector contains all of the elements in the specified
Collection.
11
void copyInto(Object[] anArray)
Copies the components of this vector into the specified array.
12
Object elementAt(int index)
Returns the component at the specified index.
13
Enumeration elements()
Returns an enumeration of the components of this vector.
14
void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold
at least the number of components specified by the minimum capacity
argument.
15
boolean equals(Object o)
Compares the specified Object with this vector for equality.
16
Object firstElement()
Returns the first component (the item at index 0) of this vector.
17
Object get(int index)
Returns the element at the specified position in this vector.
18
int hashCode()
Returns the hash code value for this vector.
19
int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality
using the equals method.
20
int indexOf(Object elem, int index)
Searches for the first occurence of the given argument, beginning the
search at index, and testing for equality using the equals method.
21
void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified
index.
22
booleanisEmpty()
Tests if this vector has no components.
23
Object lastElement()
Returns the last component of the vector.
24
int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this
vector.
25
int lastIndexOf(Object elem, int index)
Searches backwards for the specified object, starting from the specified
index, and returns an index to it.
26
Object remove(int index)
Removes the element at the specified position in this vector.
27
boolean remove(Object o)
Removes the first occurrence of the specified element in this vector, If the
vector does not contain the element, it is unchanged.
28
booleanremoveAll(Collection c)
Removes from this vector all of its elements that are contained in the
specified Collection.
29
void removeAllElements()
Removes all components from this vector and sets its size to zero.
30
booleanremoveElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this
vector.
31
void removeElementAt(int index)
removeElementAt(int index).
32
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.
33
boolean retainAll(Collection c)
Retains only the elements in this vector that are contained in the specified
Collection.
34
Object set(int index, Object element)
Replaces the element at the specified position in this vector with the
specified element.
35
void setElementAt(Object obj, int index)
Sets the component at the specified index of this vector to be the specified
object.
36
void setSize(int newSize)
Sets the size of this vector.
37
int size()
Returns the number of components in this vector.
38
List subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive, and
toIndex, exclusive.
39
Object[] toArray()
Returns an array containing all of the elements in this vector in the correct
order.
40
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this vector in the correct
order; the runtime type of the returned array is that of the specified array.
41
String toString()
Returns a string representation of this vector, containing the String
representation of each element.
42
void trimToSize()
Trims the capacity of this vector to be the vector's current size.
Example
The following program illustrates several of the methods supported by this collection
−
Import java.util.*;
Public class VectorDemo{
v.addElement(newInteger(1));
v.addElement(newInteger(2));
v.addElement(newInteger(3));
v.addElement(newInteger(4));
System.out.println("Capacity after four additions:
"+v.capacity());
v.addElement(newDouble(5.45));
System.out.println("Current capacity: "+v.capacity());
v.addElement(newDouble(6.08));
v.addElement(newInteger(7));
System.out.println("Current capacity: "+v.capacity());
v.addElement(newFloat(9.4));
v.addElement(newInteger(10));
System.out.println("Current capacity: "+v.capacity());
v.addElement(newInteger(11));
v.addElement(newInteger(12));
System.out.println("First element: "+(Integer)v.firstElement());
System.out.println("Last element: "+(Integer)v.lastElement());
if(v.contains(newInteger(3)))
System.out.println("Vector contains 3.");
Output
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
Java - The Stack Class
• Stack is a subclass of Vector that implements a standard last-in, first-out
stack.
• Stack only defines the default constructor, which creates an empty stack.
• Stack includes all the methods defined by Vector, and adds several of its
own.
• Apart from the methods inherited from its parent class Vector, Stack defines
the following methods −
1
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns
false if the stack contains elements.
2
Object peek( )
Returns the element on the top of the stack, but does not remove it.
3
Object pop( )
Returns the element on the top of the stack, removing it in the process.
4
Object push(Object element)
Pushes the element onto the stack. Element is also returned.
5
int search(Object element)
Searches for element in the stack. If found, its offset from the top of the
stack is returned. Otherwise, -1 is returned.
Example
The following program illustrates several of the methods supported by this collection
−
Import java.util.*;
Public class StackDemo{
Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
Java - The Hashtable Class
1
Hashtable( )
This is the default constructor of the hash table it instantiates the Hashtable
class.
2
Hashtable(int size)
This constructor accepts an integer parameter and creates a hash table that
has an initial size specified by integer value size.
3
Hashtable(int size, float fillRatio)
This creates a hash table that has an initial size specified by size and a fill
ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full the hash table can be before it is resized upward.
4
Hashtable(Map < ? extends K, ? extends V > t)
This constructs a Hashtable with the given mappings.
Apart from the methods defined by Map interface, Hashtable defines the following
methods −
2
Object clone( )
Returns a duplicate of the invoking object.
3
boolean contains(Object value)
Returns true if some value equal to the value exists within the hash table.
Returns false if the value isn't found.
4
Boolean containsKey(Object key)
Returns true if some key equal to the key exists within the hash table.
Returns false if the key isn't found.
5
Boolean containsValue(Object value)
Returns true if some value equal to the value exists within the hash table.
Returns false if the value isn't found.
6
Enumeration elements( )
Returns an enumeration of the values contained in the hash table.
7
Object get(Object key)
Returns the object that contains the value associated with the key. If the key
is not in the hash table, a null object is returned.
8
boolean isEmpty( )
Returns true if the hash table is empty; returns false if it contains at least
one key.
9
Enumeration keys( )
Returns an enumeration of the keys contained in the hash table.
10
Object put(Object key, Object value)
Inserts a key and a value into the hash table. Returns null if the key isn't
already in the hash table; returns the previous value associated with the key
if the key is already in the hash table.
11
void rehash( )
Increases the size of the hash table and rehashes all of its keys.
12
Object remove(Object key)
Removes the key and its value. Returns the value associated with the key. If
the key is not in the hash table, a null object is returned.
13
int size( )
Returns the number of entries in the hash table.
14
String toString( )
Returns the string equivalent of a hash table.
Example
The following program illustrates several of the methods supported by this data
structure −
Import java.util.*;
Public class HashTableDemo{
balance.put("Zara",newDouble(3434.34));
balance.put("Mahnaz",newDouble(123.22));
balance.put("Ayan",newDouble(1378.00));
balance.put("Daisy",newDouble(99.22));
balance.put("Qadir",newDouble(-19.08));
while(names.hasMoreElements()){
str =(String)names.nextElement();
System.out.println(str +": "+balance.get(str));
}
System.out.println();
// Deposit 1,000 into Zara's account
bal=((Double)balance.get("Zara")).doubleValue();
balance.put("Zara",newDouble(bal+1000));
System.out.println("Zara's new balance: "+balance.get("Zara"));
}
}
Output
Qadir: -19.08
Zara: 3434.34
Mahnaz: 123.22
Daisy: 99.22
Ayan: 1378.0
1
Properties( )
This constructor creates a Properties object that has no default values.
2
Properties(Properties propDefault)
Creates an object that uses propDefault for its default values. In both
cases, the property list is empty.
Apart from the methods defined by Hashtable, Properties define the following
methods −
1
String getProperty(String key)
Returns the value associated with the key. A null object is returned if the
key is neither in the list nor in the default property list.
2
String getProperty(String key, String defaultProperty)
Returns the value associated with the key; defaultProperty is returned if the
key is neither in the list nor in the default property list.
3
void list(PrintStreamstreamOut)
Sends the property list to the output stream linked to streamOut.
4
void list(PrintWriterstreamOut)
Sends the property list to the output stream linked to streamOut.
5
void load(InputStreamstreamIn) throws IOException
Inputs a property list from the input stream linked to streamIn.
6
Enumeration propertyNames( )
Returns an enumeration of the keys. This includes those keys found in the
default property list, too.
7
Object setProperty(String key, String value)
Associates value with the key. Returns the previous value associated with
the key, or returns null if no such association exists.
8
void store(OutputStreamstreamOut, String description)
After writing the string specified by description, the property list is written to
the output stream linked to streamOut.
Example
The following program illustrates several of the methods supported by this data
structure −
Import java.util.*;
Public class PropDemo{
capitals.put("Illinois","Springfield");
capitals.put("Missouri","Jefferson City");
capitals.put("Washington","Olympia");
capitals.put("California","Sacramento");
capitals.put("Indiana","Indianapolis");
Output
The capital of Missouri is Jefferson City.
The capital of Illinois is Springfield.
The capital of Indiana is Indianapolis.
The capital of California is Sacramento.
The capital of Washington is Olympia.
Constructor Description
Methods Description
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type is Object.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is Laxmi"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
import java.util.*;
Output:
Next token is : my
Note: The StringTokenizer class is deprecated now. It is recommended to use the
split() method of the String class or the Pattern class that belongs to the
java.util.regex package.
StringTokenizer1.java
import java.util.StringTokenizer;
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class
"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
Demonstrating
methods
from
StringTokenizer
class
The above Java program shows the use of two methods hasMoreTokens() and
nextToken() of StringTokenizer class.
Example of hasMoreElements() method of the
StringTokenizer class
• This method returns the same value as hasMoreTokens() method of
StringTokenizer class.
• The only difference is this class can implement the Enumeration interface.
StringTokenizer2.java
import java.util.StringTokenizer;
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
while (st.hasMoreElements())
{
System.out.println(st.nextToken());
}
}
}
Output:
Hello
everyone
I
am
a
Java
developer
StringTokenizer3.java
import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
/* Prints the elements from the String */
System.out.println(st.nextElement());
}
}
}
Output:
Hello
Everyone
Have
a
nice
day
StringTokenizer4.java
import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Prints the number of tokens present in the String */
System.out.println("Total number of Tokens: "+st.countTokens());
}
}
Output: