You are on page 1of 37

Java Packages

Objectives

NIIT

In this lesson, you will learn about:


Generic Types
Exploring the java.util package

Packages and Streams

Lesson 1A / Slide 1 of 30

Java Packages
Generic Types:
A geneic type represents a class or an interface that a type-safe. It means it can
act on any data type.
Generic types are designed to act upon only objects not with primitive data
types.
Since it acts upon any datatype, in the place of the datatype, we use a generic
parameter like <T> or <GT>

Generic class:
represents a class that is typesafe.
class MyClass<T>{
T obj;
}
Here T represents any datatype. The datatype is specified by the
programmer at the time of creating objects of MyClass as
MyClass<String> obj=new MyClass<String>();

NIIT

Packages and Streams

Lesson 1A / Slide 2 of 30

Java Packages
Generic Types:
Generic methods:
represents a method that is typesafe.
<T> void display(){
// method code;
}

NIIT

Packages and Streams

Lesson 1A / Slide 3 of 30

Java Packages
The Collection Framework:
It is possible to store group of objects into an array.
for ex:- Student arr[]=new Student[50];
And we can retrieve them again but we cant do certain operations very
effectively such as inserting and deleting objects, etc from an array.
The alternative way is using an object, instead of an array, to store a group of
objects. Such an object is called Collection Object or Container Object
A Collection object stores references of other objects not store the copies of
other objects.

java.util

collection classes
collection objects
NIIT

Packages and Streams

Lesson 1A / Slide 4 of 30

Java Packages
The Collection Interface
A collection is an object that contains a group of objects within it.
These objects are called the elements of the collection. The elements
of a collection descend from a common parent type.
Collections have an advantage over arrays that collections can grow to
any size unlike arrays.
The following constructors are used for the collection interface:
CollectionName(): Creates an empty collection. A void

constructor does not accept any argument.


CollectionName(Collection coll): Creates a new collection
that accepts a collection as an argument and returns the
collection containing the same elements as the collection
argument.

NIIT

Packages and Streams

Lesson 1A / Slide 5 of 30

Java Packages
Inteface type

Implementation classes

Set <T>

HashSet <T>
LinkedHashSet <T>

List <T>

Stack <T> ; LinkedList <T>


ArrayList <T> ; Vector <T>

Queue <T>

LinkedList <T>

Map <K,V>

HashMap <K,V>
HashTable <K,V>

NIIT

Packages and Streams

Lesson 1A / Slide 6 of 30

Java Packages
Exploring java.util Package
Class

Description

StringToken
izer

Provides method to break strings into tokens.

Arrays

Provides various methods to perform various operations on arrays,


such as searching and sorting.

Date

Encapsulates Date and Time Information

Calendar

Provides support for date conversion and can be extended to provide


conversion for specific calendar systems.

GregorianCa
lendar

Provides the standard calendar used worldwide. It is a subclass of the


Calendar class.

NIIT

Packages and Streams

Lesson 1A / Slide 7 of 30

Java Packages
Sets: A Set represents a group of elements arranged just like an array. A Set will
not allow duplicate elements.

Lists: Lists are like Sets. But lists allow duplicate values to be stored.

Queues: It represents FIFO order

Maps: Stores elements in the form of key and value pairs.


Retrieving Elements from Collections:
Following are the 4 ways to retrieve any element from a collection object.
Using for each loop.
Using Iterator interface
Using ListIterator interface
Using Enumeration interface

NIIT

Packages and Streams

Lesson 1A / Slide 8 of 30

Java Packages
for each: to repeatedly executes a group of statements

Iterator: it has 3 Methods

NIIT

Methods

Description

boolean hasNext( )

Returns true if exists otherwise false

element next( )

Returns the next element

void remove()

Removes the current element

Packages and Streams

Lesson 1A / Slide 9 of 30

Java Packages
ListIterator: it contains Methods to retrieve elements both in forward and
reverse directions.

Methods

Description

boolean hasNext( )

Returns true if exists otherwise false

boolean hasPrevious( ) Returns true if previous element exists


element next( )

Returns the next element

element previous( )

Returns the previous element

void remove()

Removes the current element

Enumeration: it is like the Iterator. It has only 2 methods.

NIIT

Methods

Description

boolean hasMoreElements( )

Returns true if exists


otherwise false

element nexElement( )

Returns the next element

Packages and Streams

Lesson 1A / Slide 10 of 30

Java Packages
HashSet:
HashSet represents a set of elements. It doesnt guarantee the order of
elements.
Constructors:
HashSet()
HashSet(int capacity);

Ex:- HashSet<String> hs= new HashSet<String>();

HashSet Methods:

NIIT

boolean add( )

boolean remove()

void clear()

boolean contains( )

boolean isEmpty()

int size()

Packages and Streams

Lesson 1A / Slide 11 of 30

Java Packages
Stack Class:
A Stack represents a group of elements in LIFO ( Last in First Out) order.
Constructors:
Stack()
Ex:- Stack <Integer> stk= new Stack<Integer>();

Stack Methods:
boolean empty()

element peek( )

element pop( )

int search(element)

NIIT

Packages and Streams

element push(element)

Lesson 1A / Slide 12 of 30

Java Packages
LinkedList Class:
A LinkedList represents a group of elements in

the form of nodes. Each


node will have 3 fields one data field and two link fields.

Constructors:
LinkedList()
Ex:- LinkedList <String> llist= new LinkedList<String>();

LinkedList Methods:
boolean add(obj)

void add(pos,obj)

void addFirst(obj)

void addLast(obj)

obj removeFirst()

obj removeLast()

obj remove(int pos)

void clear()

obj get(int pos)

obj getFirst()

obj getFirst()

obj set(int pos, obj)

int indexOf(obj)

int lastIndexOf(obj)

Object[] toArray()

NIIT

Packages and Streams

Lesson 1A / Slide 13 of 30

Java Packages
ArrayList Class:
A ArrayList is like an array, which can grow in memory dynamically.
ArrayList is not Synchronized
Constructors:
ArrayList()
Ex:- ArrayList <String> arlst= new ArrayList<String>(); // cap - 10

ArrayList Methods:
boolean add(obj)

void add(pos,obj)

obj remove(int pos)

boolean remove(obj)

void clear()

obj get(int pos)

obj set(int pos, obj)

int size()

boolean contains(obj)

int indexOf(obj)

int lastIndexOf(obj) Object[] toArray()

NIIT

Packages and Streams

Lesson 1A / Slide 14 of 30

Java Packages
Vector Class:
A Vector also stores elements (objects) similar to ArrayList, but vector is
synchronized.

Constructors:
Vector()
Ex:- Vector<String> v= new Vector<String>(); // default capacity - 10

Vector Methods:
boolean add(obj)

void add(pos,obj)

obj remove(int pos)

boolean remove(obj)

void clear()

obj get(int pos)

voidremoveAllElements( )

String toString()

boolean removeElement(obj)

obj set(int pos, obj)

int size()

boolean contains(obj)

int indexOf(obj)

int lastIndexOf(obj) Enumerator elements()

NIIT

Packages and Streams

Lesson 1A / Slide 15 of 30

Java Packages
HashMap / HasTable Class:
HashMap / HashTable is a Collection that stores elements in the form of
key-value pairs.
Keys should be unique.
HashMap is not Synchronized, where as HashTable is Synchronized.

Constructors:
HashMap<K,V>()
Ex:- HashMap<String, Integer> hm= new HashMap<String,Integer>();

HashMap Methods:
value put(key,value)

value get(obj key)

value remove(obj key)

boolean isEmpty()

void clear()

int size()

Set <k> keySet()

Converts into Set where only keys will be stored


Collection <v> values()

NIIT

Packages and Streams

Lesson 1A / Slide 16 of 30

Java Packages
Arrays Class:
Arrays class provides methods to perform certain operations on any one
dimensional array.

Arrays Class Methods: All methods are static


void sort(array)

void sort(array, int start, int end)

int binarySearch(array , element)

Boolean equals(array1, array2)

array copyOf(array, int n)

void fill(array, value)

NIIT

Packages and Streams

Lesson 1A / Slide 17 of 30

Java Packages
StreamTokenizer Class

The
one
The
The
and

StreamTokenizer class breaks up an input stream into tokens and allows


token to be read at one time.
tokens are delimited by set of characters, such as end of line character.
StreamTokenizer class can recognize identifiers, numbers, quoted strings,
various comment styles.

Syn:- StringTokenizer st=new StringTokenizer(String str, delimeter);


Ex:- StringTokenizer st=new StringTokenizer(str,,);
Ex:- StringTokenizer st=new StringTokenizer(str,, .);

StringTokenizer Methods:
int countTokens()

NIIT

boolean hasMoreTokens()

Packages and Streams

String nextToken()

Lesson 1A / Slide 18 of 30

Java Packages

StreamTokenizer Class

Methods of the StreamTokenizer class

Methods

Description

void eolIsSignificant(boolean flag)

NIIT

Collaborate

Ensures that end of line or new line


characters are treated as tokens. If the
flag parameter is true then
StreamTokenizer treats the new line
character as token. If the flag is false
then end of line character is treated as
white space that separates the tokens.

Lesson 2C / Slide 19 of 22

Java Packages

StreamTokenizer Class(Contd.)
Methods

Description

void wordChars(int start, int end)

Specifies the range of characters that


can build the words or tokens. The
start and end parameters specifies
the range of valid characters.

void whitespaceChars(int start, int


end)

Specifies all the characters in the


range specified by the start and end
parameters as white space
characters.
Returns the next token from the
input stream of the StreamTokenizer.
It throws an IOException if an I/O
error occurs.

int nextToken()

NIIT

Collaborate

Lesson 2C / Slide 20 of 22

Java Packages

StreamTokenizer Class(Contd.)

The StreamTokenizer class defines four int constants


TT_EOF: indicates that an end of stream is reached.
TT_WORD: indicates that a word token is read.
TT_EOL: indicates that an end of line is read.
TT_NUMBER: indicates that a number token is read.

The StreamTokenizer class has the ttype as an instance variable that contains
the type of token read by the nextToken() method.

For a single character token the ttype variable contains the integer form of that
single character token. For a quoted string token the ttype variable can have
values, such as TT_EOF, TT_EOL, TT_WORD, and TT_NUMBER.

NIIT

Collaborate

Lesson 2C / Slide 21 of 22

Java Packages

Date and Calendar Class

NIIT

The Date class encapsulates the system date and time information.
The Java Development Kit (JDK) included various methods for converting dates
into year, month, day, hour, minute, or seconds.
Some of the constructors of the Date class are:
Date(): Initializes an object with the current date and time.
Date(long ms): Accepts an argument that represents the number of
milliseconds that have elapsed since January 1, 1970. This date is used as
the reference date for calculating the number of millseconds that have
passed till the current date.

Collaborate

Lesson 1C / Slide 22 of 20

Java Packages

Date and Calendar Class


Ex: Date d= new Date();
Now, d contains the system date and time. Once Date class object is created, it
should be formatted using the following methods of java.text package
DateFormat fmt=DateFormat.getDateInstance(formatconst , region);
DateFormat fmt=DateFormat.getTimeInstance(formatconst , region);
DateFormat fmt=DateFormat.getDateTimeInstance(formatconst,formatconst,
region);

Formatconsts:
DateFormat.FULL ; DateFormat.LONG ; DateFormat.MEDIUM ; DateFormat.SHORT

region
Locale.UK; Locale.US, Locate.CHINA, Locale.CANADA, etc.
NIIT

Collaborate

Lesson 1C / Slide 23 of 20

Java Packages

Date and Calendar Class(Contd.)

The following table lists the various methods of the Date class:
Method

Description

boolean before(Date date)

boolean after(Date date)

long getTime()

NIIT

Collaborate

Returns true if the invoking date


object contains a date that is
earlier than the one specified by
the date variable.
Returns true if the invoking date
object contains a date that is later
than the one specified by the date
variable.
Returns the milliseconds that have
elapsed since January 1, 1970,
00.00.00 GMT.

Lesson 1C / Slide 24 of 20

Java Packages

Date and Calendar Class(Contd.)


Method

Description

boolean equals(Object)

Returns true if the current object and


the argument represents the same date.

int compareTo(Date date)

Returns 0 if the value of the invoking


object is equal to the value specified by
the date parameter. The compareTo()
method returns a positive value if the
invoking object is later than the date
parameter and a negative value when it
is earlier than the date parameter.

NIIT

Collaborate

Lesson 1C / Slide 25 of 20

Java Packages

Date and Calendar Class(Contd.)

The GregorianCalendar class derived from the abstract Calendar class that
defines the various methods that provide information about the interpretation of
time as year, month, day, hour, minute, or second.

GregorianCalendar
GregorianCalendar
GregorianCalendar
GregorianCalendar

calendar=new
calendar=new
calendar=new
calendar=new

GregorianCalendar();
GregorianCalendar(Locale.UK);
GregorianCalendar(int year,int month, int day);
GregorianCalendar(1985,Calendar.MARCH,10);

You can retrieve this as a Date object by calling the getTime() method

Date now=calendar.getTime();

NIIT

Collaborate

Lesson 1C / Slide 26 of 20

Java Packages
Setting the Date and Time
You have a setTime() method that you can pass a Date object to set a
GregorianCalendar object to the time specified by the Date object

GregorianCalendar calendar=new GregorianCalendar();


calendar.setTime(date); // here date is the object of Date class

You have several overloaded versions of the set() method of setting various
components of the Date and Time.

set(int year,int month,int day);


set(int year,int month,int day,int hour, int minute, int second);
GregorianCalendar calendar=new GregorianCalendar();
calendar.set(1995,10,25);

NIIT

Collaborate

Lesson 1C / Slide 27 of 20

Java Packages
Setting the Date and Time
set(int field, int value);
Field

Value

DATE or
DAY_OF_MONTH

Can be set to a value 1 to 31

MONTH

Can have the value of JANUARY, FEBRUARY, etc,


through to DECEMBER, or values of 0 to 11

DAY_OF_WEEK

SUNDAY,MONDAY,etc or values 1 to 7

YEAR

Year for example, 2010

DAY_OF_YEAR

Can be set to a value 1 to 366

HOUR

A value from 1 t0 12 in a.m or p.m

HOUR_OF_DAY

A valur from 0 to 23

NIIT

Collaborate

Lesson 1C / Slide 28 of 20

Java Packages
Setting the Date and Time
set(int field, int value);
Field

Value

MINUTE

A value from 0 to 59

SECOND

A value from 0 to 59

AM_PM

AM or PM or values of 0 and 1

ZONE_OFFSET

Indicating GMT

GregorianCalendar calendar=new GregorianCalendar();


calendar.set(Calendar.DATE,15);
calendar.set(Calendar.MONTH,3); or calendar.set(Calendar.MONTH,MARCH);
calendar.set(Calendar.YEAR,2008);

NIIT

Collaborate

Lesson 1C / Slide 29 of 20

Java Packages
Getting the Date and Time
You can get the information such as the day, the month, and the year from a
GregorianCalendar object by using the get() method

GregorianCalendar calendar=new GregorianCalendar();


calendar.setTime(new Date());
int day = Calendar.get(Calendar.DAY_OF_WEEK);
int mm= Calendar.get(Calendar.MONTH);

NIIT

Collaborate

Lesson 1C / Slide 30 of 20

Java Packages

Date and Calendar Class(Contd.)

The following table lists a few methods of defined by the Calendar class:

Method

Description

boolean after(Object objCal)

Returns true if the invoking Calendar


object contains a date that is later than
the date specified by the objCal
parameter.
Returns true if the invoking Calendar
object contains a date that is earlier
than the date specified by the objCal
parameter.

boolean before(Object objCal)

NIIT

Collaborate

Lesson 1C / Slide 31 of 20

Java Packages

Date and Calendar Class (Contd.)


Method

Description

boolean equals(Object objCal)

Returns true if the invoking Calendar


object contains a date that is equal
to the date specified by the objCal
parameter.

final void clear()

Clears all the time components in


the invoking object.

final Date getTime()

Returns the Date object equivalent


to the time of the invoking Calendar
object.

NIIT

Collaborate

Lesson 1C / Slide 32 of 20

Java Packages

Random Class

The Random class is a generator of pseudo-random numbers. These are called


pseudo-random numbers because they are simply uniformly distributed
sequences.
The Random class enables you to create multiple random number generators that
are independent of one another.
Any Random object can generate pseudo-random numbers of type int, long, float,
or double. These numbers are created using an algorithm that takes a seed and
grows a sequence of numbers from it.

Constructors:
Random()
Random(long seed)

// sequence not repeatable


// sequence repeatable

The default constructor will create an object that uses the current time from your
computer clock as the starting value for generating pseudo-random numbers
The other constructor accepts an argument of type long that will be used as seed.
NIIT

Collaborate

Lesson 1C / Slide 33 of 20

Java Packages
Random Operations

The public methods provided by a Random object are:

Method

Desciption

int nextInt()

Returns the next int random number

int nextInt(int limit)

next int random num with in the range 0 to limit

float nextFloat()

Returns the next float random number

double nextDouble()

Returns the next double random number

long nextLong()

Returns the next long random number

boolean nextBoolean() Returns the next boolean random number


Void setSeed(long)

Sets the seed value

double nextGaussian() Returns a double value centered at 0.0 with a


standard deviation of 1.0
NIIT

Collaborate

Lesson 1C / Slide 34 of 20

Java Packages

Summary
In this lesson, you learned:

NIIT

Packages enable you to organize the class files provide by Java.


The various built-in packages of the Java programming language are:
java.lang
java.util
java.io
java.applet
java.awt
java.net
The packages created by users are called user-defined packages.
The import statement with the package name enables you to inform the
compiler about the region of classes.
The java.lang package provides a number of classes and interfaces that are
fundamental to Java programming.
Packages and Streams

Lesson 1A / Slide 35 of 30

Java Packages

Summary (Contd.)

NIIT

Some of the classes defined in the java.lang package are :


The various built-in packages of the Java programming language are:
Object
Class
System
Wrapper
Character
Integer
Math
String
The java.util package provides various utility classes and interfaces that
support date/calendar operations, String manipulation, parsing, and basic
event processing

Packages and Streams

Lesson 1A / Slide 36 of 30

Java Packages

Summary (Contd.)

NIIT

Some of the classes defined in the java.util package are :


BitSet
Date
Calendar
GregorianCalendar
Random
StringTokenizer
Arrays
The various interfaces defined in the java.util package are:
Collection
List
Set
SortedSet

Packages and Streams

Lesson 1A / Slide 37 of 30