Wrapper Classes: Primitive Data Type Wrapper Class
Wrapper Classes: Primitive Data Type Wrapper Class
Number is an abstract class whose sub classes are wrapper classes that are shown in the above table.
Method Description
byte byteValue()
short shortValue()
int intValue()
Converts the value of this Number object to the primitive data type returned.
long longValue()
float floatValue()
double doubleValue()
All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the
wrapper classes except Boolean and Character are subclasses of an abstract class called Number, whereas
Boolean and Character are derived directly from the Object class.All of the wrapper classes except Character
provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String
representation of the type being constructed.
1
Collections in JAVA
import java.io.*;
class wrapperdemo
{
public static void main(String[] args)
{
int x=20;
Integer i = new Integer(x);
System.out.println(i);
//converts integer variable x into object
int y = i.intValue();
//retrives value present in object i
System.out.println(y);
double d=20.5;
Double d1 = new Double(d);
//converts integer variable x into object
System.out.println(d1);
double k = d1.doubleValue();
//retrives value present in object k
System.out.println(k);
}
}
_____________________________________________________________________________
UNIT- III
Exploring Java Language, Collections Overview, Collections Interfaces, Collections Classes, Iterators, Random
Access Interface, Maps, Comparators, Arrays, Legacy classes and interfaces, String tokenizer, BitSet , Date,
Calendar, Timer
____________________________________________________________________________________________
Collections in java is a framework that provides an architecture to store and manipulate the group of
objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can
be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set,
List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet etc).
2
Collections in JAVA
Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and
manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme.
Thus, the way that you used Vector was different from the way that you used Properties.
1. The framework had to be high-performance. The implementations for the fundamental collections
(dynamic arrays, linked lists, trees, and hash tables) are highly efficient.
2. The framework had to allow different types of collections to work in a similar manner and with a high
degree of interoperability.
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
Hierarchy of Collection Framework :The java.util package contains all the classes and interfaces for Collection
framework.
3
Collections in JAVA
Implementation
Interface type
classes
HashSet<T>
Set<T> LinkedHashSet<T>
TreeSet<T>
this table represents the interfaces and
their implementation classes of Collection
Stack<T>
frame work
LinkedList<T>
ArrayList<T>
Vector<T>
List<T>
Queue<T> LinkedList<T>
HashMap<k,v>
Map<k,v>
HashTable<k,v>
There are many methods declared in the Collection interface. They are as follows:
2 public boolean addAll(collection c) is used to insert the specified collection elements in the invoking collection.
4 public boolean removeAll(Collection is used to delete all the elements of specified collection from the invoking
c) collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking collection except the specified
collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
4
Collections in JAVA
element)
9 public boolean containsAll(Collection is used to search the specified collection in this collection.
c)
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
ArrayList al=new ArrayList();//creating old non-generic arraylist
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of
objects in it. If you try to add another type of object, it gives compile time error.
import java.util.*; output:
class TestCollection1{
public static void main(String args[]){
Ravi
Vijay
Ravi
Ajay 5
Collections in JAVA
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
public class TestCollection7{ output:
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>(); Ravi
al.add("Ravi"); Vijay
al.add("Vijay"); Ravi
al.add("Ravi"); Ajay
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
ArrayList LinkedList
1) ArrayList internally uses dynamic array to store the LinkedList internally uses doubly linked list to
elements. store the elements.
6
Collections in JAVA
3) ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.
import java.util.*; Ajay
Ravi
Vijay
7
Collections in JAVA
class TestCollection11{
public static void main(String args[]){
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Difference between List and Set: List can contain duplicate elements whereas Set contains unique elements
only.
8
Collections in JAVA
9
Collections in JAVA
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
10
Collections in JAVA
11
Collections in JAVA
HashMap Hashtable
2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key
or value.
5) We can make the HashMap as synchronized by calling this Hashtable is internally synchronized
code and can't be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);
Iterators
1. for-each loop
2. Iterator interface
3. ListIterator interface
4. Enumeration interface
for-each loop:
the difference between for loop and for-each loop is that for loop is INDEX BASED RETRIEVAL and for-each
loop is OBJECT BASED RETRIEVAL.
Syntax of for-each loop is:
for(variable : collection-object)
{
Statements;
}
Here, the variable assumes each element of the collection-object and the loop is executed as many times
as there are number of elements in the collection-object.
If the collection-object has ‘n’ elements the loop is executed exactly ‘n’ times and variable stores each
element in each step.
Iterator interface:
Iterator is an interface that contains methods to retrieve the elements one by one from a collection object.
It has 3 methods:
12
Collections in JAVA
1. boolean hasNext() : this method returns true if the iterator has more elements
2. element next() : this method returns the next element in the iterator
3. void remove() : this method removes from the collection the last element returned by the iterator.
ListIterator Interface:
.
it is as interface that contains methods to retrieve elements from a collection object in both forward and
reverse direction ( top-bottom and bottom-top). It has these methods:
1. boolean hasNext() : this method returns true if the iterator has more elements in forward direction
2. boolean hasPrevious() : this method returns true if the iterator has more elements in backward
direction
3. element next() : this method returns the next element in the iterator
4. element previous() : this method returns the previous element in the iterator
5. void remove() : this method removes from the collection the last element returned by the iterator.
Enumeration Interface:
It is useful to retrieve elements one by one just like iterator. It has the following methods:
1. boolean hasMoreElements() : this method tests if the enumeration has any more elements or not.
2. element nextElement() : this returns next element that is available in the enumeration.
Comparators
The java.util package offers an interface called comparator that is useful to impose total ordering on a
collection of elements.
It can be used to sort the elements ( objects ) of an array into ascending or descending order.
Comparator can be written as:
interface Comparator<T>
The compare( ) method, shown here, compares two elements for order:
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are
equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value
is returned. The method can throw a ClassCastException if the types of the objects are
not compatible for comparison. By overriding compare( ), you can alter the way that
objects are ordered. For example, to sort in reverse order, you can create a comparator
that reverses the outcome of a comparison.
THE JAVA LIBRARY
13
Collections in JAVA
The equals( ) method, shown here, tests whether an object equals the invoking comparator
obj is the object to be tested for equality. The method returns true if obj and the invoking object are both
Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary,
and most simple comparators will not do so.
As the following output shows, the tree is now stored in reverse order:
FEDCBA
The original version of java.util did not include the collections framework. Instead, it defined several classes and
an interface that provided an ad hoc method of storing objects. With the addition of collections by Java 2, several
of the original classes were reengineered to support the collection interfaces.
Thus, they are fully compatible with the framework. While no classes have actually been deprecated, one has been
rendered obsolete. Of course, where a collection duplicates the functionality of a legacy class, you will usually want
to use the collection for new code. In general, the legacy classes are supported because there is still code
that uses them. One other point: None of the collection classes are synchronized, but all the legacy classes are
synchronized. This distinction may be important in some situations. Of course, you can easily synchronize
collections, too, by using one of the algorithms provided by Collections.
14
Collections in JAVA
STRING TOKENIZER
The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of
discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class
provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner.
StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can
enumerate the individual tokens contained in it using StringTokenizer.
To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are
characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—
for example, “,;:” sets the delimiters to a comma, semicolon, and colon.
The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage
return.
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the
second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is
true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not
returned.
Delimiters are not returned as tokens by the first two forms.
int countTokens( ) : Using the current set of delimiters, the method determines the number of tokens
left to be parsed and returns the result.
boolean hasMoreElements( ) : Returns true if one or more tokens remain in the string else returns
false
boolean hasMoreTokens( ) : Returns true if one or more tokens remain in the string else returns false
Object nextElement( ) : Returns the next token as an Object.
String nextToken( ) : Returns the next token as a String.
String nextToken(String delimiters) : Returns the next token as a String and sets the delimiters
string to that specified by delimiters.
import java.io.*;
import java.util.*;
class Count
{
public static void main(String[] a) throws IOException
{
String s;
int lc=1,wc=0,cc=0;
15
Collections in JAVA
A BitSet class creates a special type of array that holds bit values.
This array can increase in size as needed.
This makes it similar to a vector of bits.
The BitSet constructors are shown here:
BitSet( )
BitSet(int size)
public java.util.BitSet();
public java.util.BitSet(int);
public void flip(int);
public void flip(int, int);
public void set(int);
public void set(int, boolean);
public void set(int, int);
public void set(int, int, boolean);
public void clear(int);
public void clear(int, int);
public void clear();
public boolean get(int);
public java.util.BitSet get(int, int);
public int nextSetBit(int);
public int nextClearBit(int);
public int length();
public boolean isEmpty();
public boolean intersects(java.util.BitSet);
public int cardinality();
public void and(java.util.BitSet);
public void or(java.util.BitSet);
public void xor(java.util.BitSet);
public void andNot(java.util.BitSet);
public int hashCode();
public int size();
public boolean equals(java.lang.Object);
public java.lang.Object clone();
public java.lang.String toString();
DATE CLASS
16
Collections in JAVA
Date class is useful to display the date and time at that particular moment.
When an object is created to Date class it contains the system date and time by default
To create an object the syntax is
This method is useful to store format information for date value into DateFormat object fmt
This method is useful to store format information for time into DateFormat object fmt
To specify the date and time of Date class object the method used is format( ) method
The preceeding format( ) method will apply the format which is in fmt object to the Date class object ‘d’.
the formatted date and time will appear as a string in variable ‘str’. In the preceeding DateFormat
methods we used ‘formatconst’ parameter which represents one of the following values:
‘region’ means one of the following values for countries in the world:
Locale.US, Locale.UK, Locale.CHINA etc.,,,
CALENDAR CLASS
The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to
a number of useful components.
Some examples of the type of information that can be provided are: year, month, day, hour, minute, and
second.
It is intended that subclasses of Calendar will provide the specific functionality to interpret
time information according to their own rules.
This is one aspect of the Java class library that enables you to write programs that can operate in several
international environments.
An example of such a subclass is GregorianCalendar.
Calendar provides no public constructors.
Calendar defines several protected instance variables.
areFieldsSet is a boolean that indicates if the time components have been set.
fields is an array of ints that holds the components of the time.
isSet is a boolean array that indicates if a specific time component has been set.
time is a long that holds the current time for this object.
isTimeSet is a boolean that indicates if the current time has been set.
Calendar.MONTH
Calendar.DATE
Calendar.YEAR
Calendar.MINUTE
17
Collections in JAVA
Calendar.HOUR
Calendar.SECOND
Calendar.AM_PM etc.,,
18