Oop CH 9-12
Oop CH 9-12
E 4th
BINARY I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API
In this Java File IO tutorial, we show you how to read and write binary files using both
legacy File I/O API and new File I/O API (NIO). The legacy API (classes in the java.io.*
package) is perfect for manipulating low-level binary I/O operations such as reading and
writing exactly one byte at a time, whereas the NIO API (classes in the java.nio.*
package) is more convenient for reading and writing the whole file at once, and of course,
faster than the old File I/O API.
HANDLING IN JAVA
syntax:
PrintWriter o =new printwriter(“input.txt”);
o.print(“I love my country”);
Example:
Scanner i = new Scanner(new File(input.txt));
System.out.println(i.nextline());
CONCEPT OF 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 the
console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message to the console.
o System.out.println("simple message");
o System.err.println("error message");
Let's see the code to get input from console.
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
The java.io package contains all the classes required for input output
operations.
All streams represent an input source and an output destination.
The stream in the java.io package supports all the datatype including
primitive.
A stream can be defined as a sequence of data.
SREZ Page 1
Object Oriented Programming -I B.E 4th
All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the computer
screen. If you are aware of C or C++ programming languages, then you must be aware of
three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the
following three standard streams −
Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
System.out.
Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented as
System.err.
FILEINPUTSTREAM
Java FileInputStream class obtains input bytes from a file.
It is used for reading streams of raw bytes such as image data.
For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video etc.
SREZ Page 2
Object Oriented Programming -I B.E 4th
SREZ Page 3
Object Oriented Programming -I B.E 4th
FILEOUTPUTSTREAM
Methods of fileoutputstream
SREZ Page 4
Object Oriented Programming -I B.E 4th
FILTERINPUTSTREAM
Java FilterInputStream class implements the InputStream. It contains different sub classes
as BufferedInputStream, DataInputStream for providing additional functionality. So it is
less used individually.
Java FilterInputStream class declaration
Let's see the declaration for java.io.FilterInputStream class
o public class FilterInputStream extends InputStream
Example
import java.io.*;
public class FilterExample {
public static void main(String[] args) throws IOException {
File data = new File("D:\\testout.txt");
SREZ Page 5
Object Oriented Programming -I B.E 4th
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to java programming
Output:
Welcome to java programming
FILTEROUTPUTSTREAM
Example
import java.io.*;
public class FilterExample {
public static void main(String[] args) throws IOException {
File data = new File("D:\\testout.txt");
FileOutputStream file = new FileOutputStream(data);
FilterOutputStream filter = new FilterOutputStream(file);
String s="Welcome to java.";
byte b[]=s.getBytes();
SREZ Page 6
Object Oriented Programming -I B.E 4th
filter.write(b);
filter.flush();
filter.close();
file.close();
System.out.println("Success...");
}
}
Output:
Success...
DATAINPUTSTREAM
Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read
by a data input stream.
Java DataInputStream class declaration
o Let's see the declaration for java.io.DataInputStream class:
o public class DataInputStream extends FilterInputStream implements DataInput
Example
package com.java;
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
SREZ Page 7
Object Oriented Programming -I B.E 4th
DATAOUTPUTSTREAM
Java DataOutputStream class allows an application to write primitive Java data types to
the output stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read
by a data input stream.
Java DataOutputStream class declaration
Let's see the declaration for java.io.DataOutputStream class:
o public class DataOutputStream extends FilterOutputStream implements
DataOutput
Java DataOutputStream class methods
SREZ Page 8
Object Oriented Programming -I B.E 4th
Example
package com.java;
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
BUFFEREDINPUTSTREAM
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
The important points about BufferedInputStream are:
SREZ Page 9
Object Oriented Programming -I B.E 4th
o When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.
➔Java BufferedInputStream class declaration
Let's see the declaration for Java.io.BufferedInputStream class:
public class BufferedInputStream extends FilterInputStream
Example
package com.java;
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
SREZ Page 10
Object Oriented Programming -I B.E 4th
}catch(Exception e){System.out.println(e);}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Java Programming
Output:
Java Programming
BUFFEREDOUTPUTSTREAM
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. So, it
makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see
the syntax for adding the buffer in an OutputStream:
o OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO
Package\\testout.txt"));
Java BufferedOutputStream class declaration
o Let's see the declaration for Java.io.BufferedOutputStream class:
o public class BufferedOutputStream extends FilterOutputStream
Example
package com.java;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to Java World.";
byte b[]=s.getBytes();
SREZ Page 11
Object Oriented Programming -I B.E 4th
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
Success
testout.txt
Welcome to Java World.
OBJECT I/O
Serializable is a marker interface (has no data member and method). It is used to "mark"
Java classes so that the objects of these classes may get a certain capability. The
Cloneable and Remote are also marker interfaces.
It must be implemented by the class whose object you want to persist.
The String class and all the wrapper classes implement the java.io.Serializable interface
by default.
SREZ Page 12
Object Oriented Programming -I B.E 4th
This class is used for reading and writing to randomaccessfile. A random access file
behaves like a large array of bytes.
There is a cursor implied to the array called file pointer, by moving the cursor we do the
read write operations. If end-of-file is reached before the desired number of byte has been
read than EOFException is thrown. It is a type of IOException.
Constructor
Methods
Example
import java.io.IOException;
import java.io.RandomAccessFile;
SREZ Page 13
Object Oriented Programming -I B.E 4th
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
Recursion
SREZ Page 14
Object Oriented Programming -I B.E 4th
1. we need one helper method where we will pass original string , prefix and one list for
result.
2. we will use recursion here. and base case is string is null, in that case we will be returning
prefix+orginal string.
3. initially prefix is null and here we will check the 1st character of string is character or not
if character we remove that character from original string and will add the same character to
prefix and will call uppercase and lowercase method.
Tail Recursion
A tail-recursive function is just a function whose very the last action is a call to itself.
Tail-Call Optimisation(TCO) lets us convert regular recursive calls into tail calls to
make recursions practical for large inputs, which was earlier leading to stack overflow
error in normal recursion scenario
SREZ Page 15
Object Oriented Programming -I B.E 4th
Generics
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid
types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String arrays
and so on, to sort the array elements.
SREZ Page 16
Object Oriented Programming -I B.E 4th
{
this.val=val;
}
public getval()
{
return val;
}
public setval()
{
val=newValue;
}
private T val; //variable defined as a generic
}
Generic methods
Generic methods are methods that introduce their own type parameters.
This is similar to declaring a generic type, but the type parameter scope is limited to the
method where it is declared. Static and non-static generic methods are allowed, as well as
generic class constructors.
The syntax for a generic method includes a list of type parameters, inside angle brackets,
which appears before the method's return type. For static generic methods, the type
parameter section must appear before the method's return type.
Let's see a simple example of java generic method to print array elements. We are using here
E to denote the element.
Output :
10
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T
There may be times when you want to restrict the types that can be used as type
arguments in a parameterized type. For example, a method that operates on numbers
might only want to accept instances of Number or its subclasses. This is what bounded
type parameters are for.
o Sometimes we don’t want whole class to be parameterized, in that case we can
create java generics method. Since constructor is a special kind of method, we can
use generics type in constructors too.
o Suppose we want to restrict the type of objects that can be used in the
parameterized type. For example in a method that compares two objects and we
want to make sure that the accepted objects are Comparables.
o The invocation of these methods is similar to unbounded method except that if we
will try to use any class that is not Comparable, it will throw compile time error .
SREZ Page 18
Object Oriented Programming -I B.E 4th
Unbounded Wildcards
The unbounded wildcard type represents the list of an unknown type such as List<?>.
This approach can be useful in the following scenarios: -
o When the given method is implemented by using the functionality provided in the
Object class.
o When the generic class contains the methods that don't depend on the type
parameter.
SREZ Page 19
Object Oriented Programming -I B.E 4th
Example
import java.util.Arrays;
import java.util.List;
for(Object o:list)
{
System.out.println(o);
}
List<Integer> l1=Arrays.asList(1,2,3);
System.out.println("displaying the Integer values");
display(l1);
List<String> l2=Arrays.asList("One","Two","Three");
System.out.println("displaying the String values");
display(l2);
}
}
Output :
displaying the Integer values
1
2
3
displaying the String values
One
Two
Three
This wildcard type is specified using the wildcard character (?), for example, List. This is
called a list of unknown type. These are useful in the following cases
o When writing a method which can be employed using functionality provided in
Object class.
o When the code is using methods in the generic class that don’t depend on the type
parameter
SREZ Page 20
Object Oriented Programming -I B.E 4th
The purpose of lower bounded wildcards is to restrict the unknown type to be a specific
type or a supertype of that type. It is used by declaring wildcard character ("?") followed
by the super keyword, followed by its lower bound.
Syntax
List<? super Integer>
Here,
? is a wildcard character.
super, is a keyword.
Integer, is a wrapper class.
Suppose, we want to write the method for the list of Integer and its supertype (like
Number, Object). Using List<? super Integer> is suitable for a list of type Integer or any
of its superclasses whereas List<Integer> works with the list of type Integer only. So,
List<? super Integer> is less restrictive than List<Integer>.
Example
SREZ Page 21
Object Oriented Programming -I B.E 4th
In this example, we are using the lower bound wildcards to write the method for
List<Integer> and List<Number>.
import java.util.Arrays;
import java.util.List;
for(Object n:list)
{
System.out.println(n);
}
}
public static void main(String[] args) {
List<Integer> l1=Arrays.asList(1,2,3);
System.out.println("displaying the Integer values");
addNumbers(l1);
List<Number> l2=Arrays.asList(1.0,2.0,3.0);
System.out.println("displaying the Number values");
addNumbers(l2);
}
}
Output :
displaying the Integer values
1
2
3
displaying the Number values
1.0
2.0
3.0
SREZ Page 22
Object Oriented Programming -I B.E 4th
Restrictions on generics
SREZ Page 23
Object Oriented Programming -I B.E 4th
Collection Overview
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Hierarchy Of Collection Framework
SREZ Page 1
Object Oriented Programming -I B.E 4th
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
SREZ Page 2
Object Oriented Programming -I B.E 4th
List Interface
SREZ Page 3
Object Oriented Programming -I B.E 4th
Set Interface
The set interface is used to define the set of elements.It extends the collection
interface.This interface defined unique elements.hence if any duplicate elements in tried
to insert in the set then the add() method return itself.
Sortedset Interface
A set is used to provide a particular ordering on its element. The elements are ordered
either by using a natural ordering or by using a Comparator. All the elements which are
inserted into a sorted set must implement the Comparable interface.
The set's iterator will traverse the set in an ascending order. Several other operations are
provided in order to make best use of ordering. All the elements must be mutually
comparable.
Map Interface
This interface maps a unique key elements to the value.Thus map interface represent a key
value pair.
Sortedmap Interface
The SORTEDMAP is inherited from the Map interface.In this interface the elements are
stored in ascending order.This Stored order is based on the key.
Iterators
SREZ Page 4
Object Oriented Programming -I B.E 4th
Methods
SREZ Page 5
Object Oriented Programming -I B.E 4th
The comparable interface is used to compare two objects of two different classes
This interface is present in java.util.* package
This interface defines two methods -
1.Compare()
2.equals()
Syntax:
public void sort(List list,Comparator c)
Method Description
Int Compare(Object obj1,Object obj2) This method compares obj1 and obj2.It
returns 0 if these objects are equal.It
returns positive value if obj1>obj2.It returns
negative if obj1<obj2
boolean equals(Object obj) The object is tested for equality.This
method returns the true object and the
invoking object are both Comparator
objects and use the same ordering
Lists
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and access
the elements from the list.
SREZ Page 6
Object Oriented Programming -I B.E 4th
Arraylist
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types.
The ArrayList class maintains the insertion order and is non-synchronized. The elements
stored in the ArrayList class can be randomly accessed.
SREZ Page 7
Object Oriented Programming -I B.E 4th
Linkedlist
Java LinkedList class uses a 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
The important points about Java LinkedList are:
● Java LinkedList class can contain duplicate elements.
● Java LinkedList class maintains insertion order.
● Java LinkedList class is non synchronized.
● In Java LinkedList class, manipulation is fast because no shifting needs to occur.
● Java LinkedList class can be used as a list, stack or queue.
SREZ Page 8
Object Oriented Programming -I B.E 4th
SREZ Page 9
Object Oriented Programming -I B.E 4th
Collection class contains static methods to perform common operations in collection and
a list.
Static Methods for List
Method Description
Void sort(List list) Sort the given list
void sort(List list,Comparator c) Sorts the given list with the Comparator
Int BinarySearch(List list,Object key) Searches the key in the given list using
binary search
void reverse(List list) Reverse the given list.
void shuffle(List list) Shuffle the specified list randomly
void copy(List dest,List src) Copies the source list to a destination list
Void fill(List list,Object obj) Fills the list with object
Method Description
Object max(Collection c) This method returns the max object in
collection.
Object max(Collection c,Comparator cm) This method returns the max object in
collection using Comparator.
Object min(Collection c) This method returns the min object in
collection.
Object min(Collection c,Comparator cm) This method returns the minobject in
collection using Comparator.
boolean disjoint(Collection c1,Collection c2) This function returns true if c1 and c2 have
no element in common.
SREZ Page 10
Object Oriented Programming -I B.E 4th
VECTOR
Java Vector class comes under the java.util package. The vector class
implements a growable array of objects. Like an array, it contains the component
that can be accessed using an integer index.
Vector is very useful if we don't know the size of an array in advance or we need
one that can change the size over the lifetime of a program.
Vector implements a dynamic array that means it can grow or shrink as required.
It is similar to the ArrayList, but with two differences-
o Vector is synchronized.
o The vector contains many legacy methods that are not the part of a
collections framework
Java Vector Class Declaration
1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
1. void addElement(Object element): It inserts the element at the end of the Vector.
2. int capacity(): This method returns the current capacity of the vector.
3. int size(): It returns the current size of the vector.
4. void setSize(int size): It changes the existing size with the specified size.
5. boolean contains(Object element): This method checks whether the specified
element is present in the Vector. If the element is been found it returns true else false.
6. boolean containsAll(Collection c): It returns true if all the elements of collection c
are present in the Vector.
7. Object elementAt(int index): It returns the element present at the specified location
in Vector
.
Methods used in vector
1. Object first Element(): It is used for getting the first element of the vector.
2. Object lastElement(): Returns the last element of the array.
3. Object get(int index): Returns the element at the specified index.
4. boolean isEmpty(): This method returns true if Vector doesn’t have any element.
5. boolean removeElement(Object element): Removes the specified element from
vector.
6. boolean removeAll(Collection c): It Removes all those elements from vector
which are present in the Collection c.
7. void setElementAt(Object element, int index): It updates the element of
specified index with the given element.
SREZ Page 11
Object Oriented Programming -I B.E 4th
SREZ Page 12
Object Oriented Programming -I B.E 4th
Stack
Java Stack is LIFO object. It extends Vector class but supports only five operations. Java
Stack class has only one constructor which is empty or default constructor. So, when we
create a Stack, initially it contains no items that mean Stack is empty.
Stack internally has a pointer: TOP, which refers to the top of the Stack element. If Stack
is empty, TOP refers to the before first element location. If Stack is not empty, TOP
refers to the top element.
SREZ Page 13
Object Oriented Programming -I B.E 4th
Queues
SREZ Page 14
Object Oriented Programming -I B.E 4th
1. boolean add(E e): This method adds the specified element at the end of Queue. Returns
true if the the element is added successfully or false if the element is not added that basically
happens when the Queue is at its max capacity and cannot take any more elements.
2. E element(): This method returns the head (the first element) of the Queue.
3. boolean offer(object): This is same as add() method.
4. E remove(): This method removes the head(first element) of the Queue and returns its
value.
5. E poll(): This method is almost same as remove() method. The only difference between
poll() and remove() is that poll() method returns null if the Queue is empty.
6. E peek(): This method is almost same as element() method. The only difference between
peek() and element() is that peek() method returns null if the Queue is empty.
Priority queues
we have seen how a Queue serves the requests based on FIFO(First in First out). Now the
question is: What if we want to serve the request based on the priority rather than
FIFO? In a practical scenario this type of solution would be preferred as it is more
dynamic and efficient in nature. This can be done with the help of PriorityQueue, which
SREZ Page 15
Object Oriented Programming -I B.E 4th
serves the request based on the priority that we set using Comparator.
SREZ Page 16
Object Oriented Programming -I B.E4th
Sets
Hash Set
This class implements the Set interface, backed by a hash table (actually a HashMap
instance). It makes no guarantees as to the iteration order of the set; in particular, it does
not guarantee that the order will remain constant over time. This class permits the null
element.
This class is not synchronized. However it can be synchronized explicitly like this:
Set s = Collections.synchronizedSet(new HashSet(...));
1. HashSet doesn’t maintain any order, the elements would be returned in any random order.
2. HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old
value would be overwritten.
3. HashSet allows null values however if you insert more than one nulls it would still return
only one null value.
4. HashSet is non-synchronized.
5. The iterator returned by this class is fail-fast which means iterator would throw
ConcurrentModificationException if HashSet has been modified after creation of iterator, by
any means except iterator’s own remove method.
SREZ Page 1
Object Oriented Programming -I B.E4th
HashSet Example
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output :
Five
One
Four
Two
Three
SREZ Page 2
Object Oriented Programming -I B.E4th
LinkedHashSet Class
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.
The important points about the Java LinkedHashSet class are:
Java LinkedHashSet class contains unique elements only like HashSet.
Java LinkedHashSet class provides all optional set operations and permits null
elements.
Java LinkedHashSet class is non-synchronized.
Java LinkedHashSet class maintains insertion order.
LinkedHashSet Example
FileName: LinkedHashSet1.java
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
SREZ Page 3
Object Oriented Programming -I B.E4th
Tree Set:
TreeSet is similar to HashSet except that it sorts the elements in the ascending order while
HashSet doesn’t maintain any order.
TreeSet allows null element but like HashSet it doesn’t allow. Like most of the other
collection classes this class is also not synchronized, however it can be synchronized
explicitly like this:
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
TreeSet is being implemented using a binary search tree, which is self-balancing just like
a Red-Black Tree.
Therefore, operations such as a search, remove, and add consume O(log(N)) time. The
reason behind this is there in the self-balancing tree. It is there to ensure that the tree
height never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of
SREZ Page 4
Object Oriented Programming -I B.E4th
the efficient data structures in order to keep the large data that is sorted and also to do
operations on it.
As already mentioned above, the TreeSet class is not synchronized. It means if more than
one thread concurrently accesses a tree set, and one of the accessing threads modify it,
then the synchronization must be done manually.
It is usually done by doing some object synchronization that encapsulates the set.
However, in the case where no such object is found, then the set must be wrapped with
the help of the Collections.synchronizedSet() method. It is advised to use the method
during creation time in order to avoid the unsynchronized access of the set.
The following code snippet shows the same.
TreeSet treeSet = new TreeSet();
Set syncrSet = Collections.synchronziedSet(treeSet);
Example
FileName: TreeSet1.java
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Mina");
al.add("Rina");
al.add("Tina");
al.add("Rina");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Mina
Rina
Tina
Comparing The Performance Of Sets And Lists
1)List is an ordered collection it maintains the insertion order, which means upon displaying
the list content it will display the elements in the same order in which they got inserted into
the list.
SREZ Page 5
Object Oriented Programming -I B.E4th
Set is an unordered collection, it doesn’t maintain any order. There are few
implementations of Set which maintains the order such as LinkedHashSet (It
maintains the elements in insertion order).
2) List allows duplicates while Set doesn’t allow duplicate elements. All the
elements of a Set should be unique if you try to insert the duplicate element in
Set it would replace the existing value.
4) List allows any number of null values. Set can have only a single null value at most.
5) ListIterator can be used to traverse a List in both the directions(forward and backward)
However it can not be used to traverse a Set. We can use Iterator (It works with List too) to
traverse a Set.
6) List interface has one legacy class called Vector whereas Set interface does not have any
legacy class.
Maps
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. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
SREZ Page 6
Object Oriented Programming -I B.E4th
Hash Table
This class implements a hash table, which maps keys to values. Any non-null object can
be used as a key or as a valuez
Hashtable is similar to HashMap except it is synchronized. Hashtable class declaration
SREZ Page 7
Object Oriented Programming -I B.E4th
Points to remember
A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains values based
on the key.
Java Hashtable class contains unique elements.
Java Hashtable class doesn't allow null key or value.
Java Hashtable class is synchronized.
The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Example
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Tina");
hm.put(102,"Mina");
hm.put(101,"Riya");
hm.put(103,"Siya");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Siya
102 riya
101 Mina
100Tina
Hash Map
Java HashMap class implements the map interface by using a hash table
It inherits AbstractMap class and implements Map interface.
Points to remember
SREZ Page 8
Object Oriented Programming -I B.E4th
SREZ Page 9
Object Oriented Programming -I B.E4th
Example
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output :
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes
SREZ Page 10
Object Oriented Programming -I B.E4th
Treemap
SREZ Page 11
Object Oriented Programming -I B.E4th
Example
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
100 Amit
101 Vijay
102 Ravi
103 Rahul
SREZ Page 12
Object Oriented Programming -I B.E4th
Chapter 12 : Concurrency
Introduction To Thread:
A thread is a:
Thread Vs Process
Thread Process
Thread is a light weight Process is heavy weighted
Process Process
Threads do not require separate address space Each process requires separate address space
for its execution. it runs the address space of to execute
the process to which it belongs to.
SREZ Page 13
Object Oriented Programming -I B.E4th
The start method creates the system resources, necessary to run the thread, schedules the
thread to run, and calls the thread’s run method.
A thread becomes “Not Runnable” when one of these events occurs:
o If sleep method is invoked.
o The thread calls the wait method.
o The thread is blocking on I/O.
A thread dies naturally when the run method exits .
SREZ Page 14
Object Oriented Programming -I B.E4th
In Java, a thread always exists in any one of the following states. These states are:
New
Active
Blocked / Waiting
Timed Waiting
Terminated
1. New:
Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
2. Active:
When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.
i) Runnable:
A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the
duty of the thread scheduler to provide the thread time to run, i.e., moving the thread
the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread.
Each and every thread runs for a short span of time and when that allocated time slice
is over, the thread voluntarily gives up the CPU to the other thread, so that the other
threads can also run for their slice of time.
Whenever such a scenario occurs, all those threads that are willing to run, waiting for
their turn to run, lie in the runnable state. In the runnable state, there is a queue where
the threads lie.
ii) Running:
When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.
3. Blocked or Waiting:
Whenever a thread is inactive for a span of time (not permanently) then, either the
thread is in the blocked state or is in the waiting state.
When the main thread invokes the join() method then, it is said that the main thread is
in the waiting state. The main thread then waits for the child threads to complete their
tasks.
When the child threads complete their job, a notification is sent to the main thread,
which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and the
chosen thread is then given the opportunity to run.
SREZ Page 15
Object Oriented Programming -I B.E4th
4. Timed Waiting:
Sometimes, waiting for leads to starvation.
For example, a thread (its name is A) has entered the critical section of a code and is not
willing to leave that critical section. In such a scenario, another thread (its name is B) has
to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B.
Thus, thread lies in the waiting state for a specific span of time, and not forever. A real
example of timed waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time runs out, the thread
wakes up and start its execution from when it has left earlier.
5. Terminated:
A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread
is dead, and there is no way one can respawn (active after kill) the dead thread.
SREZ Page 16
Object Oriented Programming -I B.E4th
Creation Of Thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Public void run()
{
//statements to implements thread
}
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Method Names:
SREZ Page 17
Object Oriented Programming -I B.E4th
Output:
thread is running...
The multiple threads can be created both by extending thread class and by implementing
the runnable interface.
SREZ Page 18
Object Oriented Programming -I B.E4th
Java thread pool manages the pool of worker threads. It contains a queue that keeps
tasks waiting to get executed. We can use ThreadPoolExecutor to create thread pool in
Java.
Java thread pool manages the collection of Runnable threads. The worker threads execute
Runnable threads from the queue. java.util.concurrent.Executors provide factory and
support methods for java.util.concurrent.Executor interface to create the thread pool in
java.
Executors is a utility class that also provides useful methods to work with
ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes
through various factory methods.
Steps to be followed
1. Create a task(Runnable Object) to execute
2. Create Executor Pool using Executors
3. Pass tasks to Executor Pool
4. Shutdown the Executor Pool
SREZ Page 19
Object Oriented Programming -I B.E4th
//importing classes
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
while (!executorService.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
Output :
Thread Synchronization
In many cases concurrently running threads share data and two threads try to do
operations on the same variables at the same time. This often results in corrupt data as
two threads try to operate on the same data.
A popular solution is to provide some kind of lock primitive. Only one thread can acquire
a particular lock at any particular time. This can be achieved by using a keyword
“synchronized” .
By using the synchronize only one thread can access the method at a time and a second
call will be blocked until the first call returns or wait() is called inside the synchronized
method.
SREZ Page 20
Object Oriented Programming -I B.E4th
SREZ Page 21
Object Oriented Programming -I B.E4th
SREZ Page 22