You are on page 1of 107

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

By.
G.Praveen Kumar
Assit.Prof , IT Dept.
SNIST.

G.Praveen ITDept-SNIST 1
UNIT III

1.Packages: Definition, types of packages


2.Creating and importing a user defined package
3.Introduction to I/O programming
4.DataInputStream, DataOutputStream
5.FileInputStream, FileOutputStream, BufferedReader.
6.Collections: interfaces, Implementation classes, Algorithms ( sorting and

searching).

G.Praveen ITDept-SNIST 2
Objective:-
1.Create and import packages
2.Understand different streams
3.To study and implement various classes and interfaces of Java Collections
Framework.

G.Praveen ITDept-SNIST 3
Packages in java:- A java package is a group of similar types of classes,
interfaces and sub-packages.

Advantages of Packages:- Packages are Like header files


1.With a single import statement, all the classes and interfaces can be obtained
into our program
2.Unlike a header file, Java permits to import even a single class also.
3.Avoids namespace problems. Two classes of the same name cannot be put
in the same package but can be placed in two different packages.
4.Access between the classes can be controlled. Using
packages, restrictions can be imposed on the access of other package classes.
Access specifies work on package boundaries (between the classes of other
packages).

G.Praveen ITDept-SNIST 4
Cont…Advantage of package:-

5.We can find all the related classes and interfaces in a single space. Searching
and identification will be easier.
6.Packages and sub-packages are the easiest way to organize the classes.
7.Package is used to categorize the classes and interfaces so that they can be
easily maintained
8.Application development time is less, because reuse the code
9.Application memory space is less (main memory)
10.Application execution time is less
11.Application performance is enhance (improve)
12.Redundancy (repetition) of code is minimized
13.Package provides access protection.
14.Package removes naming collision.

G.Praveen ITDept-SNIST 5
Importing All/Single Class:- Packages have an advantage over header files of
C-lang. A package allows importing a single class also instead of importing all.
C-lang does not have this ease of getting one function from a header file.

import java.net.*; // imports all the classes and interfaces


import java.awt.evnet.*; // imports all the classes and interfaces
Import java.net.Socket;// imports only Socket class
import java.awt.event.WindowEvent; // imports only Window Event class

Note: While importing a single class, asterisk (*) should no be used.

G.Praveen ITDept-SNIST 6
Resolving Namespace Problems:- By placing the same class in two
different packages, which Java permits, namespace problems can be
solved. Namespace is the area of execution of a program in RAM.
The Date class exists in two packages
 java.util and java.sql. Importing these two packages in a program
gives ambiguity problem to the compiler.

G.Praveen ITDept-SNIST 7
Need of package:-The purpose of package concept is to provide common
classes and interfaces for any program separately. In other words if we want to
develop any class or interface which is common for most of the java programs
than such common classes and interfaces must be place in a package

G.Praveen ITDept-SNIST 8
Packages in Java are the way to organize files when a project has many
modules. Same like we organized our files in Computer. For example we
store all movies in one folder and songs in other folder, here also we store
same type of files in a particular package for example in awt package have
all classes and interfaces for design GUI components.

SNIST

G.Praveen ITDept-SNIST 9
Type of package:- Package are classified into two type

1. Predefined or built-in package


2. User defined package

Predefined or built-in package:- These are the package which are already
designed by the Sun Microsystem and supply as a part of java API, every
predefined package is collection of predefined classes, interfaces and sub-package

User defined package:- A package is design by the user is known as user defined
package. User defined package are those which are developed by java programmer
and supply as a part of their project to deal with common requirement.

G.Praveen ITDept-SNIST 10
PACKAGE
EXAMPLE CLASSES FUNCTIONALITY (PURPOSE)
NAME

These classes are indispensable for


every Java program. For this reason,
java.lang System, String, Object, Thread, Exception etc.
even if this package is not imported,
JVM automatically imports.
These are called as utility (service) classes and are used very
java.util
frequently in coding.

FileInputStream, FileOutputStream, FileReader, FileWriter, These classes are used in all I/O
java.io
RandomAccessFile, BufferedReader, BufferedWriter etc. operations including keyboard input.

URL, ServerSocket, Socket, DatagramPacket, DatagramSocket Useful for writing socket programming
java.net
etc. (LAN communication).
Required for developing applets that
java.applet AppletContext, Applet, AudioStub, AudioClip etc participate on client-side in Internet
(Web) programming.
Essential for developing GUI
java.awt Button, Choice, TextField, Frame, List, Checkbox etc.
applications.
Without these classes, it is impossible
MouseListener, ActionListener, ActionEvent, WindowAdapter
java.awt.event to handle events generated by GUI
etc.
components
Required for database access in JDBC
java.sql DriverManager, Statement, Connection, ResultSet etc
applications.
G.Praveen ITDept-SNIST 11
1. java.applet 11. java.text
2. java.awt 12. java.util
3. java.beans 13. java.util.zip
4. java.io 14.javax.sql
5. java.lang 15.javax.swing
6. java.lang.ref
7. java.math
8. java.net
9. java.nio
10. java.sql
G.Praveen ITDept-SNIST 12
Rules to create user defined package:-
package statement should be the first statement of any package program.
Choose an appropriate class name or interface name and whose modifier must
be public.
Any package program can contain only one public class or only one public
interface but it can contain any number of normal classes.
Package program should not contain any main class (that means it should not
contain any main())
modifier of constructor of the class which is present in the package must be
public. (This is not applicable in case of interface because interface have no
constructor.)
The modifier of method of class or interface which is present in the package
must be public (This rule is optional in case of interface because interface
methods by default public)
Every package program should be save either with public class name or public
Interface name

G.Praveen ITDept-SNIST 13
Defining a Packages:- To create a package is quite easy: simply include a
package command as the first
statement in a Java source file.

Any classes declared within that file will belong to the specified package.

The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name.

This is the general form of the package statement:


Syntax: package pkg;

Example: package MyPackage;

Java uses file system directories to store packages.

G.Praveen ITDept-SNIST 14
More than one file can include the same package statement.

You can create a hierarchy of packages.

To do so, simply separate each package name from the one above it by use
of a
period.

The general form of a multileveled package statement is shown here:


package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java


development
system.

For example, a package declared as package java.awt.image; needs to be


stored in
java\awt\image on your Windows.

G.Praveen ITDept-SNIST 15
Creating a Package:-While creating a package, you should choose a name for
the package and include a package statement along with that name at the top of
every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be
only one package statement in each source file, and it applies to all types in the
file.
If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be placed in the current default package.

Compile package programs:- For compilation of package program first


we save program with public className.java and it compile using below
syntax:

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified
destination, and the compiled class files will be placed in that folder.

G.Praveen ITDept-SNIST 16
Explanations: In above syntax "-d" is a specific tool which is tell to java
compiler create a separate folder for the given package in given path. When we
give specific path then it create a new folder at that location and when we use .
(dot) then it crate a folder at current working directory.

Note: Any package program can be compile but can not be execute or run.
These program can be executed through user defined program which are
importing package program.

G.Praveen ITDept-SNIST 17
Example of package program:- Let us look at an example that creates a
package called p11. It is a good practice to use names of packages with lower
case letters to avoid any conflicts with the names of classes and interfaces.
package p11;
public class Exp
{
public int a,b;
public void show()
{
System.out.println(a+"\t"+b);
}}

Save the program Exp.java and compile the program by following command

C:\praveen>javac -d . Exp.java

Now package p11 is created and Exp.class


In the p11 package(Directory)

G.Praveen ITDept-SNIST 18
G.Praveen ITDept-SNIST 19
import Keyword:-The import keyword is used to make classes and interfaces
available and accessible to the current source code, without specifying fully
qualified package names. For example:

import java.awt.*;
import java.util.List;
import java.io.File;

The first import statement makes all classes/interfaces under package


 java.awt accessible to the current program. It uses the * wildcard character to
specify 'everything' under the package.
Likewise, the second and third import statements make the interface List and the
class File available to the current source code. It uses exact names instead of
wildcard.
The import statements must be placed on top of the source file, only after the
package statement.
 

G.Praveen ITDept-SNIST 20
import package1.package2.......*;

G.Praveen ITDept-SNIST 21
G.Praveen ITDept-SNIST 22
import p11.Exp;
class PackD1
{
public static void main(String[] args)
{
Exp ob = new Exp();
ob.a=12;
ob.b=23;
ob.show();
}}

OUTPUT:-
C:\praveen>java PackD1
12 23

G.Praveen ITDept-SNIST 23
Difference between Inheritance and package
Inheritance concept always used to reuse the feature within the program between
class to class, interface to interface and interface to class but not accessing the
feature across the program.
Package concept is to reuse the feature both within the program and across the
programs between class to class, interface to interface and interface to class.
Difference between package keyword and import keyword
Package keyword is always used for creating the undefined package and placing
common classes and interfaces.
import is a keyword which is used for referring or using the classes and interfaces
of a specific package.

G.Praveen ITDept-SNIST 24
Access Control

Java addresses four categories of visibility for class members:

Subclasses in the same package.

Non-subclasses in the same package.

Subclasses in different packages.

Classes that are neither in the same package nor subclasses.

A class has only two possible access levels: default and public.

G.Praveen ITDept-SNIST 25
Class Member Access

G.Praveen ITDept-SNIST 26
//VarProtection.java
package pack1;
public class VarProtection {
int n = 1;
private int pri = 2;
protected int pro = 3;
public int pub = 4;
public VarProtection() {
System.out.println("Individual class constructor");
System.out.println("default value is: " + n);
System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}

G.Praveen ITDept-SNIST 27
//SameSub .java:
package pack1;
class SameSub extends VarProtection{
SameSub(){
System.out.println("subclass constructor");
System.out.println("default value is: " + n);
// System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}

G.Praveen ITDept-SNIST 28
// SameDiff.java
package pack1;
class SameDiff{
SameDiff(){
VarProtection v1 = new VarProtection();
System.out.println("Delegationclass constructor");
System.out.println("default value is: " +v1. n);
// System.out.println("private value is: " +v1. pri);
System.out.println("protected value is: " +v1. pro);
System.out.println("public value is: " + v1.pub);
}
}

G.Praveen ITDept-SNIST 29
//OtherSub.java
package pack2;
import pack1.*;
class OtherSub extends VarProtection{
OtherSub(){
System.out.println("Different Package subclass
constructor");
//System.out.println("default value is: " + n);
// System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}

G.Praveen ITDept-SNIST 30
// OtherDiff.java
package pack2;
import pack1.*;
class OtherDiff{
OtherDiff(){
VarProtection v2=new VarProtection();
System.out.println("Different Package non-subclass constructor");
// System.out.println("default value is: " +v2. n);
// System.out.println("private value is: " + v2.pri);
// System.out.println("protected value is: " + v2.pro);
System.out.println("public value is: " + v2.pub);
}
}

G.Praveen ITDept-SNIST 31
// Demo package p1. To Compile:
d:\>javac –d .
package pack1;
MainTest.java
class MainTest{ To Run:
public static void main(String args[]){ d:\>java
pack1.MainTest
VarProtection v=new VarProtection();
SameDiff s2=new SameDiff();
SameSub s1=new SameSub();
}
}
package pack2;
import pack1.*;
class OtherMainTest{
public static void main(String args[]){
OtherSub os=new OtherSub();
To Compile: OtherDiff od=new OtherDiff();
d:\>javac –d . OtherMainTest.java }
To Run:
}
d:\>java pack2.OtherMainTest
Introduction to I/O programming:-The java.io package contains nearly every
class you might ever need to perform input and output (I/O) in Java. All these
streams represent an input source and an output destination. The stream in the
java.io package supports many data such as primitives, object, localized characters,
etc.
Stream:- A stream is a sequence of data .In Java a stream is composed of
bytes. It's called a stream because it is like a stream of water that continues to flow.
In java 3 streams are created for us automatically. All these streams are
attached with console.
1.Standard Streams
2.Byte Streams
3. Character Streams
Standard Streams:- Standard streams are preconnected input and output
communication channels between a computer program and its environment when it
begins execution he three I/O connections are called 
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

G.Praveen ITDept-SNIST 33
Any stream basically two kinds of Streams
1. Output Stream:- Java application uses an output stream to write data to a
destination, it may be a file, an array, peripheral device or socket.
2. Input Stream:- Java application uses an input stream to read data from a
source, it may be a file, an array, peripheral device or socket.

G.Praveen ITDept-SNIST 34
OutputStream Hierarchy:- Output Stream as following sub class each and ever
Sub class have methods.

G.Praveen ITDept-SNIST 35
OutputStream class:- OutputStream class is an abstract class. It is the super
class of all classes representing an output stream of bytes. An output stream
accepts output bytes and sends them to some sink.

Methods of OutputStream:-Output Stream as following methods

Method Description
 public void write(int)throws IOException is used to write a byte to the
current output stream.
public void write(byte[])throws IOException is used to write an array of byte to
the current output stream.
public void flush()throws IOException flushes the current output stream.
 public void close()throws IOException is used to close the current output
stream.

G.Praveen ITDept-SNIST 36
InputStream Hierarchy:- Input Stream as following sub class each and ever
Sub class have its own methods.

G.Praveen ITDept-SNIST 37
Input Stream class :- InputStream class is the superclass of all classes
representing an input stream of bytes. Applications that need to define a
subclass of InputStream must always provide a method that returns the next
byte of input.
Methods of InputStream:-Input Stream as following methods

Method Description
1. available()  This method returns an estimate of the number of bytes that
can be read (or skipped over) from this input stream without
blocking by the next invocation of a method for this input
stream.
2. Void close() This method closes this input stream and releases any system
resources associated with the stream.
3. Void mark(int method marks the current position in this input stream. A
readlimit)  subsequent invocation to the reset() method reposition the
stream to the recently marked position.
4. Abstract int read() This method reads the next byte of data from the input
stream.
5.Int read(byte[] b) This method reads some number of bytes from the input
stream and stores them into the buffer array b.
G.Praveen ITDept-SNIST 38
Method Description
5.Int read(byte[] b, This method reads up to len bytes of data from the input
int off, int len) stream into an array of bytes.
6.Void reset()  This method repositions this stream to the position at the time
the mark method was last called on this input stream.

G.Praveen ITDept-SNIST 39
Byte Streams:- Programs use byte streams to execute input and output of
8-bit bytes. All byte stream classes are descended from InputStream and
OutputStream . There are many byte stream classes

W E L C O M E S N I S T .

W E L C O M E S N I S T .

byte stream input and output.

G.Praveen ITDept-SNIST 40
BYTE STREAMS CLASS:-
STREAM CLASS DESCRIPTION
Used for Buffered Input Stream.
Buffered Input Stream

Buffered Output Stream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype


An output stream that contain method for writing java
DataOutputStream
standard data type
FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println()method

G.Praveen ITDept-SNIST 41
Byte Streams:- Java byte streams are used to perform input and output of 8-bit
bytes. Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream. Following is
an example which makes use of these two classes to copy an input file into an
output file −

G.Praveen ITDept-SNIST 42
NOTE:- Before compile above program create a text file called input2.txt

C:\praveen>copy con input2.txt


WELCOME TO IT DEPT
^Z
1 file(s) copied.

C:\praveen>javac FIOS.java

C:\praveen>type output2.txt
The system cannot find the file specified.

C:\praveen>java FIOS

C:\praveen>type output2.txt
WELCOME TO IT DEPT

C:\praveen>

G.Praveen ITDept-SNIST 43
1. BufferedInputStream Class:- BufferedInputStream class is used to read
information from stream. It internally uses buffer mechanism to make the
performance fast. And When a BufferedInputStream is created, an internal
buffer array is created.
Declaration of BufferedInputStream class :-

public class BufferedInputStream 

BufferedInputStream class constructors:-


Constructor Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and
saves it argument, the input stream
IS(object).
BufferedInputStream(InputStream IS, int It creates the BufferedInputStream with
size) a specified buffer size and saves it
argument, the input stream IS.

G.Praveen ITDept-SNIST 44
 BufferedInputStream class methods:-

Method Description
int available() It returns an estimate number of bytes that can be read
from the input stream without blocking by the next
invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream
into a specified byte array, starting with the given
offset.
void close() It closes the input stream and releases any of the
system resources associated with the stream.
void reset() It repositions the stream at a position the mark method
was last called on this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the
input stream.

G.Praveen ITDept-SNIST 45
import java.io.*;
public class BufferedIS{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("C:\\praveen\\pra.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1)
{
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
} }
Note:- Before compile the above program create a text file and pass as a argument to
the FIS

G.Praveen ITDept-SNIST 46
BufferedOutputStream Class:-Java BufferedOutputStream class is used for
buffering an output stream. It internally uses buffer to store data. It adds more
efficiency than to write data directly into a stream. And it makes the performance
fast.
Syntax:-
OutputStream os= new BufferedOutputStream(new FileOutputStream(“FILEPATH")); 
public class BufferedOutputStream
BufferedOutputStream class constructors:-
Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream


which is used for writing the data to the
specified output stream.
BufferedOutputStream(OutputStream os, It creates the new buffered output stream
int size) which is used for writing the data to the
specified output stream with a specified
buffer size.

G.Praveen ITDept-SNIST 47
Buffered OutputStream class methods:-

Method Description

void write(int b) It writes the specified byte to the buffered output


stream.

void write(byte[] b, int off, It write the bytes from the specified byte-input
int len) stream into a specified byte array, starting with
the given offset
void flush() It flushes the buffered output stream.

G.Praveen ITDept-SNIST 48
import java.io.*;
public class BufferedOS
{
public static void main(String args[])throws Exception
{
FileOutputStream fout=new FileOutputStream("C:\\praveen\\
test.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to SNIST.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

G.Praveen ITDept-SNIST 49
Data Input Stream Class:-DataInputStream class allows an application to
read primitive data from the input stream in a machine-independent way.
DataInputStream class declaration as
public class DataInputStream extends FilterInputStream implements DataInput  
Method Description
int read(byte[] b) It is used to read the number of bytes from the input
stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.

int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char
value.
double readDouble() It is used to read eight input bytes and returns a double
value.
boolean readBoolean() It is used to read one input byte and return true if byte is
non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input
stream.

G.Praveen ITDept-SNIST 50
Method Description
String readUTF() It is used to read a string that has been
encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input
stream and store them into the buffer
array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input
stream.

G.Praveen ITDept-SNIST 51
import java.io.*;
public class DIS {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("C:\\praveen\\k1.txt");
DataInputStream d1 = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
d1.read(ary);
for (byte bt : ary) { OUTPUT:- create k1.txt
char k = (char) bt; C:\praveen>copy con k12.txt
System.out.print(k+"*"); ITDEPT^Z
} } } 1 file(s) copied.

C:\praveen>javac DIS.java

C:\praveen>java DIS
I*T*D*E*P*T*
C:\praveen>

G.Praveen ITDept-SNIST 52
DataOutputStream class:-Java DataOutputStream class allows an application to write
primitive Java data types to the output stream in a machine-independent way.
DataOutputStream class declaration
public class DataOutputStream extends FilterOutputStream implements DataOutput
  
Method Description
int size() It is used to return the number of bytes written to
the data output stream.
void write(int b) It is used to write the specified byte to the
underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output
stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a
1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-
byte value.
void writeChars(String s) It is used to write string to the output stream as a
sequence of characters.
G.Praveen ITDept-SNIST 53
Method Description
void writeByte(int v) It is used to write a byte to the output stream as a
1-byte value.
void writeBytes(String s) It is used to write string to the output stream as a
sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream
using UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.

G.Praveen ITDept-SNIST 54
import java.io.*;
public class Op
{
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream("c:\\praveen\\kkk.txt");

DataOutputStream data = new DataOutputStream(file);


data.writeInt(65);
String s= new String("WELCOME");
data.writeChars(s); OUTPUT:-
data.flush(); C:\praveen>javac Op.java
data.close();
System.out.println("Succcess..."); C:\praveen>java Op
} } Succcess...

C:\praveen>type kkk.txt
AWELCOME
C:\praveen>

G.Praveen ITDept-SNIST 55
G.Praveen ITDept-SNIST 56
Collections in Java:- Collections in java is a framework and it provides an
architecture to store and manipulate the group of objects. We can perform
operations on a data such as searching, sorting, insertion, manipulation, deletion
etc.
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)
Collection represents a single unit of objects i.e. a group.

G.Praveen ITDept-SNIST 57
G.Praveen ITDept-SNIST 58
G.Praveen ITDept-SNIST 59
G.Praveen ITDept-SNIST 60
G.Praveen ITDept-SNIST 61
G.Praveen ITDept-SNIST 62
G.Praveen ITDept-SNIST 63
G.Praveen ITDept-SNIST 64
Hierarchy of Collection Framework:-

G.Praveen ITDept-SNIST 65
G.Praveen ITDept-SNIST 66
Collections Hierarchy Java

G.Praveen ITDept-SNIST
Description of fundamental interfaces of Collections Hierarchy:

Interface Brief Description Derived Classes


It forms the root interface and comes with
methods that define basic operations and Majority of all DS come under this
Collection
makes all DS as one unit (called by a common interface
name)
Subclasses of this interface have a common
Set HashSet, LinkedHashSet
feature of not allowing duplicate elements
Subclasses of this interface come with a
common feature of printing the elements in
SortedSet TreeSet
ascending order implicitly. Being sub interface
of Set, it allows only unique elements
List Subclasses allow duplicate elements LinkedList, ArrayList, Vector
Allows the subclasses to store key/value pairs. HashMap, LinkedHashMap,
Map
Does not allow duplicate keys. Hashtable
Prints elements in ascending order of keys.
SortedMap Being a sub interface of Map, it inherits the TreeMap
property of not allowing the duplicate keys.

G.Praveen ITDept-SNIST 68
G.Praveen ITDept-SNIST 69
Methods of Collection interface:-There are many methods declared in the
Collection interface.
There are many methods declared in the Collection interface.

Method Description
public boolean add(Object element) is used to insert an element in this
collection.
public boolean addAll(Collection c) is used to insert the specified
collection elements in the invoking
collection.
public boolean remove(Object is used to delete an element from
element) this collection.
public boolean removeAll(Collection is used to delete all the elements of
c) specified collection from the
invoking collection.
public boolean retainAll(Collection c) is used to delete all the elements of
invoking collection except the
specified collection.

G.Praveen ITDept-SNIST 70
Method Description
public int size() return the total number of elements in the
collection.
public void clear() removes the total no of element from the
collection.
public boolean contains(Object element) is used to search an element.
public boolean containsAll(Collection c) is used to search the specified collection in
this collection.
public Iterator iterator() returns an iterator.
public Object[] toArray() converts collection into array.
public boolean isEmpty() checks if collection is empty.
public boolean equals(Object element) matches two collection.
public int hashCode() returns the hashcode number for collection.

G.Praveen ITDept-SNIST 71
G.Praveen ITDept-SNIST 72
Iterator interface:- Iterator interface provides the facility of iterating the elements in
forward direction only.
Methods of Iterator interface

Method Description
public boolean hasNext() It returns true if iterator has more elements.
public Object next() It returns the element and moves the cursor
pointer to the next element.
public void remove() It removes the last elements returned by the
iterator. It is rarely used.

G.Praveen ITDept-SNIST 73
The List interface:-A List is ordered and may have duplicates and
Operations are exactly those for Collections

int size( );
boolean containsAll(Collection c);
boolean isEmpty( );
boolean addAll(Collection c);
boolean contains(Object e);
boolean removeAll(Collection c);
boolean add(Object e);
boolean retainAll(Collection c);
boolean remove(Object e);
void clear( );
Iterator iterator( );

Object[ ] toArray( );
Object[ ] toArray(Object a[ ]);

G.Praveen ITDept-SNIST 74
List interface is derived from Collection interface.
The subclasses of List can utilize the methods of Collection and List
interfaces.
The most used subclasses are ArrayList and LinkedList.

G.Praveen ITDept-SNIST 75
Java ArrayList class:-java ArrayList class uses a dynamic array for storing the
elements. It inherits Abstract List class and implements List interface.
The important points about Java ArrayList class are:
a.Java ArrayList class can contain duplicate elements.
b.Java ArrayList class maintains insertion order.
c.Java ArrayList class is non synchronized.
d.Java ArrayList allows random access because array works at the index basis.
e.In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Hierarchy of ArrayList class ArrayList


class extends AbstractList class which
implements List interface. The List interface
extends Collection and Iterable interfaces in
hierarchical order. …

G.Praveen ITDept-SNIST 76
Declaration of ArrayList class:- the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, Rand
omAccess, Cloneable, Serializable  

Constructors of ArrayList:-

Constructor Description
ArrayList() It is used to build an empty array
list.
ArrayList(Collection c) It is used to build an array list that is
initialized with the elements of the
collection c.
ArrayList(int capacity) It is used to build an array list that
has the specified initial capacity.

G.Praveen ITDept-SNIST 77
Methods of ArrayList:-Array List have following methods

Method Description
void add(int index, Object element) It is used to insert the specified element at the
specified position index in a list.
boolean addAll(Collection c) It is used to append 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.
void clear() It is used to remove all of the elements from
this list.
int lastIndexOf(Object o) It is used to return the index in this list of the
last occurrence of the specified element, or -1
if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of
the elements in this list in the correct order.
Object[] toArray(Object[] a) It is used to return an array containing all of
the elements in this list in the correct order.
G.Praveen ITDept-SNIST 78
Methods of ArrayList Conti…

boolean add(Object o) It is used to append the specified element to the end of a


list.
boolean addAll(int It is used to insert all of the elements in the specified
index, Collection c) collection into this list, starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.
int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance
to be the list's current size.

G.Praveen ITDept-SNIST 79
import java.util.*;
class Colle_Arrcls{
public static void main(String args[]){
ArrayList<String> list=new
ArrayList<String>();//Creating arraylist
list.add("JAVA");//Adding object in arraylist
list.add("MFCS");
list.add("EEE");
list.add("EM-III");

Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}} } OUTPUT:-
D:\sree>java Colle_Arrcls
JAVA
MFCS
EEE
EM-III

G.Praveen ITDept-SNIST 80
G.Praveen ITDept-SNIST 81
OUTPUT:-
C:\praveen>java ListDemo1
Elements exist before adding elements: true
Elements exist after adding elements: false
No. of cities: 4
cities contains Chennai: true
City at index number 3: Kochi
New size of cities after adding three elements: 7
Elements of cities after adding 3 more:
[Hyderabad, Chennai, Bengaluru, Kochi, Pune, Mumbai, Chennai]
Index of Chennai: 1
Last Index of Chennai: 6
Elements of subCities: [Bengaluru, Kochi, Pune]

Elements of subCities after two removes: [Pune]


Elements of cities after two removes: [Hyderabad, Chennai, Pune, Mumbai, Chennai
]

Size of subCities after calling clear(): 0


Elements of subCities after calling clear(): []

G.Praveen ITDept-SNIST 82
Linked List class:- Java LinkedList class uses doubly linked list to store the
elements. It provides a linked-list data structure. It inherits the AbstractList
class and implements List and Deque interfaces.

 LinkedList class can contain duplicate elements.

It maintains insertion order.

This class is non synchronized. And manipulation is fast


because no shifting needs to be occurred.

 LinkedList class can be used as list, stack or queue.

G.Praveen ITDept-SNIST 83
Declaration:-
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>
, Deque<E>, Cloneable, Serializable 

Constructors of LinkedList:-

Constructor Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection c) It is used to construct a list containing the elements
of the specified collection, in the order they are
returned by the collection's iterator.

G.Praveen ITDept-SNIST 84
Methods of LinkedList:-

Method Description
void add(int index, Object element) It is used to insert the specified element
at the specified position index in a list.
void addFirst(Object o) It is used to insert the given element at
the beginning of a list.
void addLast(Object o) It is used to append the given element
to the end of a list.
int size() It is used to return the number of
elements in a list
boolean add(Object o) It is used to append the specified
element to the end of a list.
boolean contains(Object o) It is used to return true if the list
contains a specified element.

G.Praveen ITDept-SNIST 85
Method Description
boolean remove(Object o) It is used to remove the first occurence of the
specified element in a list.
Object getFirst() It is used to return the first element in a list.
Object getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first
occurrence of the specified element, or -1 if the
list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last
occurrence of the specified element, or -1 if the
list does not contain any element.

G.Praveen ITDept-SNIST 86
G.Praveen ITDept-SNIST 87
Vector class:- This is resizable array (or) growable array. In the vector class Duplicate
objects are allowed.
 Insertion order is preserved.
Heterogeneous objects are allowed.
Null insertion is possible.
Implements Serializable, Cloneable and Random-access interfaces.
Every method present in Vector is synchronized and hence Vector is Thread safe.

Constructors:
1. Vector v=new Vector(); //Creates an empty Vector object with default initial
capacity 10.
Once Vector reaches its maximum capacity then a new Vector object will be
created with double capacity. That is "newcapacity=currentcapacity*2".
2. Vector v=new Vector(int initialcapacity);
3. Vector v=new Vector(int initialcapacity, int incrementalcapacity);
4.
Vector v=new Vector(Collection c);

G.Praveen ITDept-SNIST 88
Vector specific methods:
To add objects:
1. add(Object o);-----Collection
2.add(int index,Object o);-----List
3. addElement(Object o);-----Vector
To remove elements:
1.remove(Object o);--------Collection
2.remove(int index);--------------List
3.removeElement(Object o);----Vector
4.removeElementAt(int index);-----Vector
5.removeAllElements();-----Vector
6.clear();-------Collection
To get objects:
1.Object get(int index);---------------List
2.Object elementAt(int index);-----Vector
3.Object firstElement();--------------Vector
4.Object lastElement();---------------Vector

Other methods:
1.Int size();//How many objects are added
2.Int capacity();//Total capacity
3.Enumeration elements();
G.Praveen ITDept-SNIST 89
import java.util.*;
class VectorDemo
{ public static void main(String[] args)
{
Vector v=new Vector();
System.out.println(v.capacity());//10
for(int i=1;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity());//10
v.addElement("A");
System.out.println(v.capacity());//20
System.out.println(v);
}} OUTPUT:-
D:\sree>java VectorDemo
10
10
20
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]

G.Praveen ITDept-SNIST 90
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
G.Praveen ITDept-SNIST 91
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}}

G.Praveen ITDept-SNIST 92
OUTPUT:-
C:\praveen>java VectorDemo
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

G.Praveen ITDept-SNIST 93
The Set interface:- A Set is a collection of items that are unordered and
unique (no duplicates)
It perform operations of
•element membership (add, remove, isMember, etc.)
•manipulation (union, intersection,…)
Java has: Set – an interface
Several implementation classes, including HashSet
A Set is unordered and has no duplicates
Operations are exactly those for Collection

int size( ); boolean containsAll(Collection c);


boolean isEmpty( ); boolean addAll(Collection c); boolean
boolean contains(Object e); removeAll(Collection c);
boolean add(Object e); boolean retainAll(Collection c);
boolean remove(Object e); void clear( );
Iterator iterator( );
Object[ ] toArray( );
Object[ ] toArray(Object a[ ]);

G.Praveen ITDept-SNIST 94
import java.util.*;
public class SetExp
{
public static void main(String[] args)
{
String[ ] words = { "CP", "CPP", "DS", "JAVA", "OS", "CN","CP", "DS",
"DBMS", "CPP", "JDBC", "DAA" };
Set mySet = new HashSet();
for (int i = 0; i < words.length; i++)
{ mySet.add(words[i]);
}
for (Iterator iter = mySet.iterator(); iter.hasNext();)
{
String word = (String) iter.next();
System.out.print(word + " ");
}
System.out.println();
}}
C:\praveen>java SetExp
CPP DS DBMS OS JAVA CP DAA CN JDBC
G.Praveen ITDept-SNIST 95
import java.util.*;
public class SortedSet1
{
public static void main(String[] args)
{
String[ ] words = { "CP", "CPP", "DS", "JAVA", "OS", "CN","CP", "DS",
"DBMS",
"CPP", "JDBC", "DAA" };
SortedSet<String> mySet = new TreeSet<String>();
for (String word : words)
{
mySet.add(word); OUTPUT:-
} C:\praveen>java SortedSet1
for (String word : mySet) CN CP CPP DAA DBMS DS J
{ OS
first word : CN
System.out.print(word + " ");
last word : OS
}
System.out.println();
System.out.println("first word : "+mySet.first());
System.out.println("last word : "+mySet.last());
}}
G.Praveen ITDept-SNIST 96
HashSet class:-Java HashSet class is used to create a collection that uses a hash
table for storage. It inherits the AbstractSet class and implements Set interface.

HashSet stores the elements by using a mechanism called hashing.

HashSet contains unique elements only.

Declaration:-
public class HashSet<E> extends AbstractSet<E>
 implements Set<E>, Cloneable, Serializable  

Hierarchy of HashSet class

G.Praveen ITDept-SNIST 97
Constructors:-

Constructor Description
HashSet() It is used to construct a default
HashSet.
HashSet(Collection c) It is used to initialize the hash set
by using the elements of the
collection c.
HashSet(int capacity) It is used to initialize the capacity
of the hash set to the given integer
value capacity. The capacity grows
automatically as elements are
added to the HashSet.

G.Praveen ITDept-SNIST 98
Methods :-

Methods Description

void clear() It is used to remove all of the elements from this set.
boolean contains(Object o) It is used to return true if this set contains the specified
element.
boolean add(Object o) It is used to adds the specified element to this set if it is not
already present.
boolean isEmpty() It is used to return true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is
present.
Object clone() It is used to return a shallow copy of this HashSet instance: the
elements themselves are not cloned.
Iterator iterator() It is used to return an iterator over the elements in this set.

int size() It is used to return the number of elements in this set.

G.Praveen ITDept-SNIST 99
import java.util.*;
class Collection_Hashset{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new
HashSet<String>();
set.add("JAVA");
set.add("MFSC");
set.add("JAVA");
set.add("EEE");
//Traversing elements
Iterator<String> itr=set.iterator();
OUTPUT:-
while(itr.hasNext()){
D:\sree>javac Collection_Hashset.java
System.out.println(itr.next());
} } }
D:\sree>java Collection_Hashset
JAVA
EEE
MFSC

G.Praveen ITDept-SNIST 100


LinkedHashSet class:- LinkedHashSet class is a Hash table and Linked list
implementation of the set interface. It inherits HashSet class and implements Set
interface.

Contains unique elements only like HashSet.


Provides all optional set operations, and
permits null elements.
Maintains insertion order.

public class LinkedHashSet<E> extends HashSet<E>
 implements Set<E>, Cloneable, Serializable  

Hierarchy of LinkedHashSet class

G.Praveen ITDept-SNIST 101


Sorting in Collection:-This is used to sort the elements of
1.String objects
2.Wrapper class objects
3.User-defined class objects
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements
must be of Comparable type.

G.Praveen ITDept-SNIST 102


Map Interface:
A map contains values on the basis of key i.e. key and value pair.

Each key and value pair is known as an entry.

Map contains only unique keys.

Map is useful if you have to search, update or delete elements on


the basis of key.

G.Praveen ITDept-SNIST 103


methods of Map interface:

Method Description
is used to insert an entry in this
public Object put(Object key, Object value)
map.
is used to insert the specified map
public void putAll(Map map)
in this map.
is used to delete an entry for the
public Object remove(Object key)
specified key.
is used to return the value for the
public Object get(Object key)
specified key.
is used to search the specified key
public boolean containsKey(Object key)
from this map.
returns the Set view containing all
public Set keySet()
the keys.
returns the Set view containing all
public Set entrySet()
the keys and values.

G.Praveen ITDept-SNIST 104


import java.util.*;
public class MapDemo
{
public static void main(String[] args)
{
Map m1 = new HashMap();
m1.put("Akhil",new Double(6778.67));
m1.put("Arun",new Double(4567.765));
m1.put("Arun",new Double(8765.34));;
m1.put("Vineeth", new Double(2345.76));
m1.put("Arun",new Double(9876.768));
m1.put("Anitha",new Double(9889.54));
m1.put("Prachana",new Double(4889.54));
System.out.println(" Map Elements");
System.out.println("\t" + m1);
System.out.println(m1.containsKey("Anitha"));
m1.remove("Arun");
System.out.println("\nAfter removing Arun Map Elements");
System.out.println("\t" + m1);
System.out.println(m1.get("Akhil"));
Set s1=m1.keySet();
System.out.println(s1);

}} G.Praveen ITDept-SNIST 105


OUTPUT:-
C:\praveen>java MapDemo
Map Elements
{Arun=9876.768, Prachana=4889.54, Anitha=9889.54, Akhil=6778.67,
Vineeth =2345.76}
true

After removing Arun Map Elements


{Prachana=4889.54, Anitha=9889.54, Akhil=6778.67, Vineeth=2345.76}
6778.67
[Prachana, Anitha, Akhil, Vineeth]

G.Praveen ITDept-SNIST 106


An array is an indexed collection of fixed no of homogeneous data elements.
(or) An array represents a group of elements of same data type.
The main advantage of array is we can represent huge no of elements by using
single variable. So that readability of the code will be improved.

Limitations of Object[] array:


Arrays are fixed in size that is once we created an array there is no chance of
increasing (or) decreasing the size based on our requirement hence to use arrays
concept compulsory we should know the size in advance which may not possible
always. Arrays can hold only homogeneous data elements.

Example:
Student[] s=new Student[10000]; s[0]=new Student();//valid
s[1]=new Customer();//invalid(compile time error)

COMPILETIME ERROR :- Test.java:7: cannot find symbol Symbol: class


Customer Location: class Test s[1]=new Customer();

G.Praveen ITDept-SNIST 107

You might also like