0% found this document useful (0 votes)
14 views61 pages

Oop CH 9-12

Uploaded by

makkakuldip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views61 pages

Oop CH 9-12

Uploaded by

makkakuldip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Object Oriented Programming -I B.

E 4th

Chapter 9 : Binary I/O ,Recursion and Generics

 BINARY I/O

 INTRODUCTION TO I/O PROGRAMMING

 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

 There are two kinds of Streams


o InputStream : The InputStream is used to read data from a source.
o OutputStream : The OutputStream is used for writing data to a destination.

 TEXT AND BINARY I/O

 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.

 BINARY I/O CLASSES

 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

Java FileInputStream class declaration

1. public class FileInputStream extends InputStream

SREZ Page 3
Object Oriented Programming -I B.E 4th

 FILEOUTPUTSTREAM

 Java FileOutputStream is an output stream for writing data to a file.


 If you have to write primitive values then use FileOutputStream But for character-
oriented data, prefer FileWriter.
 But you can write byte-oriented as well as character-oriented data.

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

 Java FilterInputStream class Method

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

FileInputStream file = new FileInputStream(data);


FilterInputStream filter = new BufferedInputStream(file);
int k =0;
while((k=filter.read())!=-1){
System.out.print((char)k);
}
file.close();
filter.close();
}
}

Here, we are assuming that you have following data in "testout.txt" file:
Welcome to java programming
Output:
Welcome to java programming

 FILTEROUTPUTSTREAM

 Java FileOutputStream is an output stream used for writing data to a file.


 If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
 FileOutputStream class declaration
 Let's see the declaration for Java.io.FileOutputStream class:
o public class FileOutputStream extends OutputStream

 Java FilterOutputStream class Method

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

 Java DataInputStream class Methods

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

DataInputStream inst = new DataInputStream(input);


int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A

 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

Java BufferedInputStream class constructors

Java BufferedInputStream class methods

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

 The object I/O supports ObjectInputStream and ObjectOutputStream classes.These


classes to perform I/O operations for object in addition to primitive data types.
 The ObjectInputStream is a subclass of InputStream and implements ObjectInput and
ObjectStramConstant.
 Public ObjectInputStream(InputStream in)
 public ObjectOutputStream(OutputStream out)

 The Serializable Interface

 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

 Random Access Files

 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;

public class RandomAccessFileExample {


static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {

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

 Problem Solving Using Recursion

 Recursion in java is a process in which a method calls itself continuously. A method in


java that calls itself is called recursive method.
 It makes the code compact but complex to understand.
 Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}

SREZ Page 14
Object Oriented Programming -I B.E 4th

 Recursive Helper Methods

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

public class TailRecDemo


{
public static void main(String []args)
{
fun(3);
}
Public static void fun(int n)
{
System.out.println(n);
if(n>0)
fun(n-1);
}
}

SREZ Page 15
Object Oriented Programming -I B.E 4th

 Generics

 What is generic programming?

 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.

 What is the need for generic?


 It saves the programmers burden of creating separate methods for handling data
belonging to different data types.
 It allows the code reusability
 Compact code can be created.

Defining generic classes and interfaces

public class Test<T>


{
public Test() {val=null;}
public Test(T val)

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.

public class TestGenerics4{

public static < E > void printArray(E[] elements) {


for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };

System.out.println( "Printing Integer Array" );


printArray( intArray );

System.out.println( "Printing Character Array" );


printArray( charArray );
}
}

Output :

Printing Integer Array


SREZ Page 17
Object Oriented Programming -I B.E 4th

10
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T

 Raw types and backward compatibility

 Generic class or interface is used without specifying a concrete type.


 It enables backward compatibility with earlier versions of java
 Example:
GenericsStack stack= new GenericsStack();
This is almost equivalent to
GenericsStack <Object> stack = new GenericsStack<Object>();
 The raw types are unsafe.

 Concept of bounded type

 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

 Wildcard generic types

 The question mark (?) is known as the wildcard in generic programming


 It represents an unknown type. The wildcard can be used in a variety of situations such as
the type of a parameter, field, or local variable; sometimes as a return type. Unlike arrays,
different instantiations of a generic type are not compatible with each other, not even
explicitly.
 This incompatibility may be softened by the wildcard if ? is used as an actual type
parameter.
 There are three ways to use wildcards
1.Unbounded wildcard
2.Upper bound wildcard
3.Lower bound wildcard

 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;

public class UnboundedWildcard {

public static void display(List<?> list)


{

for(Object o:list)
{
System.out.println(o);
}

public static void main(String[] args) {

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

 Upper Bound wildcard

 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

 Lower Bounded Wildcards

 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;

public class LowerBoundWildcard {

public static void addNumbers(List<? super Integer> 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

 Erasure and restrictions on generics

 Type Erasure rules


o Replace type parameters in generic type with their bound if bounded type
parameters are used.
o Replace type parameters in generic type with Object if unbounded type
parameters are used.
o Insert type casts to preserve type safety.
o Generate bridge methods to keep polymorphism in extended generic types.

SREZ Page 22
Object Oriented Programming -I B.E 4th

Restrictions on generics

1. It cannot instantiate Generic Types with primitive data types.


2. It cannot create instance of Type Parameter
3. It cannot declare static field whose types are types parameter
4. It cannot use cast or instances of operators with parameterized types.
5. It cannot create Array of parameterized types.
6. It cannot create,catch or throw Objects of parameterized types.
7. It cannot overload a method where the formal parameter Types of Each Overloaded Erase
to the same Raw Type.

SREZ Page 23
Object Oriented Programming -I B.E 4th

Chapter 10 : List, Stacks, Queues and Priority Queues

 Collection Overview

 The Collection in Java is a framework that provides an architecture to store and


manipulate the group of objects.
 Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
 Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What Is A Collection Framework?

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

Methods of Collection interface

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

 List Interface is the subinterface of Collection. It contains index-based methods to insert


and delete elements. It is a factory of ListIterator interface.
 List Interface declaration
public interface List<E> extends Collection<E>

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

 An iterator is an interface that is used in place of Enumerations in the Java Collection


Framework. Moreover, an iterator differs from the enumerations in two ways:
1. Iterator permits the caller to remove the given elements from the specified
collection during the iteration of the elements.
2. Method names have been enhanced.
Iterator interface is a member connected with Java Collections Framework.

SREZ Page 4
Object Oriented Programming -I B.E 4th

 Methods

SREZ Page 5
Object Oriented Programming -I B.E 4th

 The Comparable Interface

 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

 Static Methods for List and Collections

 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

 Static Methods for Collection

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

int frequency(Collection c,Object o) It returns number of occurrences of


specificied element in the collection

 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

 Methods used in Vector:

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.

 Methods used in Stack


Method Description
boolean empty() If the stack is empty then it returns true ow it
returns false
Object peek() The element present at the top of the
stack is simply displayed
object push(object ele) This method is useful for pushing the
element onto the stack
object pop() This method is remove the element
present at the top of the stack

SREZ Page 13
Object Oriented Programming -I B.E 4th

int search(object ele) The desired element can be searched


using this method.

 Queues

 A Queue is designed in such a way so that the elements added to it are


placed at the end of Queue and removed from the beginning of Queue.
 The concept here is similar to the queue we see in our daily life, for example,
when a new iPhone launches we stand in a queue outside the apple store,
whoever is added to the queue has to stand at the end of it and persons are
served on the basis of FIFO (First In First Out), The one who gets the iPhone
is removed from the beginning of the queue.

SREZ Page 14
Object Oriented Programming -I B.E 4th

 Methods used in Queues

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

Chapter 11 : Sets and Maps

 Sets

 The set interface extends the collection interface


 The set is a collection having no duplicates elements
 The concrete classes of set are HashSet,LinkedHashSet and TreeSet

 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(...));

 Points to Note about 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.

Hierarchy of LinkedHashSet class


 The LinkedHashSet class extends the HashSet class, which implements the Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.
LinkedHashSet Class Declaration
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>,
Cloneable, Serializable

Constructors of Java LinkedHashSet Class

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

//Creating HashSet and adding elements


LinkedHashSet<String> set=new LinkedHashSet();
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:
One
Two
Three
Four
Five

 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(...));

The important points about the Java TreeSet class are:


 Java TreeSet class contains unique elements only like HashSet.
 Java TreeSet class access and retrieval times are quiet fast.
 Java TreeSet class doesn't allow null element.
 Java TreeSet class is non synchronized.
 Java TreeSet class maintains ascending order.
 Java TreeSet class contains unique elements only like HashSet.
 Java TreeSet class access and retrieval times are quite fast.
 Java TreeSet class doesn't allow null elements.
 Java TreeSet class is non-synchronized.
 Java TreeSet class maintains ascending order.

Internal Working of The TreeSet Class

 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.

Synchronization of The TreeSet Class

 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);

 TreeSet Class Declaration


public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
Cloneable, Serializable

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.

3) List implementations: ArrayList, LinkedList etc. Set implementations: HashSet,


LinkedHashSet, TreeSet etc.

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.

 Singleton And Unmodified Collection:

 Collections class defines three constants


-EMPTY_SET,EMPTY_LIST AND EMPTY_MAP for empty set,an empty list and
empty map.These Collections are immutable.
 The collection class also provides a method name singleton(object ob) for creating an
immutable set containing only one item
 There are some unmodifiable methods defined by Collection 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

Let's see the declaration for java.util.Hashtable class.


1. public class Hashtable<K,V> extends Dictionary<K,V> implements
Map<K,V>

Hashtable class Parameters

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Methods for HashTable

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

 Java HashMap class contains values based on the key.


 Java HashMap class contains only unique keys.
 Java HashMap class may have one null key and multiple null values.
 Java HashMap class is non synchronized.
 Java HashMap class maintains no order.
 The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

SREZ Page 8
Object Oriented Programming -I B.E4th

HashMap class declaration

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,


Cloneable, Serializable

HashMap class Parameters

K: It is the type of keys maintained by this map.


V: It is the type of mapped values.

Constructors of Java HashMap class

Methods of Java HashMap Class

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

 Difference Between Hashtable And Hashmap

 Treemap

 Java TreeMap class is a red-black tree based implementation. It provides an efficient


means of storing key-value pairs in sorted order.
 The important points about Java TreeMap class are:
 Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
 Java TreeMap contains only unique elements.
 Java TreeMap cannot have a null key but can have multiple null values.
 Java TreeMap is non synchronized.
 Java TreeMap maintains ascending order.

TreeMap class declaration

public class TreeMap<K,V> extends AbstractMap<K,V> implements


NavigableMap<K,V>

TreeMap class Parameters

● K: It is the type of keys maintained by this map.


● V: It is the type of mapped values.

SREZ Page 11
Object Oriented Programming -I B.E4th

Methods of Java TreeMap class

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:

 Facility to allow multiple activities within a single process


 Referred as lightweight process
 A thread is a series of executed statements
 Each thread has its own program counter, stack and local variables
 A thread is a nested sequence of method calls
 Its shares memory, files and per-process state

 What’s the need of a thread or why we use Threads?

 To perform asynchronous or background processing


 Increases the responsiveness of GUI applications
 Take advantage of multiprocessor systems
 Simplify program logic when there are multiple independent entities

 What happens when a thread is invoked?

 When a thread is invoked, there will be two paths of execution


 One path will execute the thread and the other path will follow the statement after the
thread invocation.
 There will be a separate stack and memory space for each thread.

 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.

 Difference Between Multithreading And Mulprocessing

SREZ Page 13
Object Oriented Programming -I B.E4th

 Thread States And Life Cycle

 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

 Explanation of Different Thread States

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
}

 Extending Thread Class

 The class should extend Java Thread class.


 The class should override the run() method.
 The functionality that is expected by the Thread to be executed is written in the run()
method.
void start(): Creates a new thread and makes it runnable.
void run(): The new thread begins its life inside this method.

 Constructors Used In Thread Class

 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

 Method Names:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.

SREZ Page 17
Object Oriented Programming -I B.E4th

 Implementing Runnable Interface

 The class should implement the Runnable interface


 The class should implement the run() method in the Runnable interface
 The functionality that is expected by the Thread to be executed is put in the run() method

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[])


{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output:
thread is running...

 Creating Multiple Threads

 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

 Creating And Executing Threads With The Executor Framework

 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;

//creating SimpleExecutor class


public class SimpleExecutor {
//main() method start
public static void main(String[] args) {
//creating an object of ExecutorService with fixed thread pool 5
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int j = 0; j < 5; j++) {
//creating instance of the Task1 class and pass a value to its constructor
Runnable task = new Task1("" + j);

//executing task using execute() method of the executor


executorService.execute(task);
}
//closing executor
executorService.shutdown();

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

 Using Synchronized Method

SREZ Page 21
Object Oriented Programming -I B.E4th

SREZ Page 22

You might also like