CSE1007-JAVA Programming - Module 4
CSE1007-JAVA Programming - Module 4
Data structures:
Java I/O streams
Working with files
Serialization and deserialization of objects
Lambda expressions
Collection framework
List, Map, Set
Generics Annotations
Files
Secondary Storage Device
Persistent Data – remains after program terminates
File (Java) – Stream of Bytes
End of File
streams
Java 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.
file handling in Java is performed by Java I/O API.
Streams
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.
Byte Stream
Handle input and output of bytes
Sequence of bytes
Ex: 5 binary format - 0101
Character Stream
Handle input and output of characters
Unicode - Internationalized
Sequence of characters
Types of Files
Binary File
Text File
Standard Streams
Java can open a file by creating an object
Constructor interacts with OS to open the file
3 Standard Stream objects associated with device
System.in Input bytes from keyboard
System.out Output character data to screen
System.err Output error message to screen
Example :
System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();
//returns ASCII code of 1st character
System.out.println((char)i);
//will print the character
Byte Stream Classes
Character Stream Classes
Hierarchy of classes In Streams
java.io (package) – File Processing
Stream classes
FileInputStream (byte-based i/p from a file)
FileOutputStream (byte-based o/p to a file)
FileReader (char-based i/p from a file)
FileWriter (char-based o/p to a file)
Inherits from
InputStream
OutputStream
Reader
Writer
Objects
ObjectInputStream
ObjectOutputStream
Character-based Stream
Scanner (i/p data from keyboard / file)
Streams
Source: mygreatlearning.com
FileOutputStream
FileOutputStream is used to create a file and write data
into it. The stream would create a file, if it doesn't
already exist, before opening it for output.
Here are two constructors which can be used to create
a FileOutputStream object.
Following constructor takes a file name as a string to
create an input stream object to write the file −
OutputStream f = new
FileOutputStream(“D:\\Sample.txt")
Following constructor takes a file object to create an
output stream object to write the file.
File f = new File(" D:\\Sample.txt ");
OutputStream f = new FileOutputStream(f);
Helper methods
Sr.N Method & Description
o.
System.out.print("Address: ");
address = br.readLine();
System.out.print("Class: ");
Class = br.readLine();
System.out.print("Age: ");
age = Integer.parseInt(br.readLine());
101 Ram
101 Ram
Generics
Parameterized types
enable to create classes, interfaces, and methods in
which the type of data upon which they operate is
specified as a parameter
A class, interface, or method that operates on a
parameterized type is called generic, as in generic class
or generic method
Generics Work Only with Objects
For example
Single class - works with different types of data
Generic Class
A class that can refer to any type is known as a generic class.
Syntax :
class class-name<type-param-list> { // ... }
For example
Class MyGen<T>{
T obj;
void display(T obj){ system.outthis.obj=obj;}
T get(){return obj;}
}
T - Type parameter <>
Generic Class
For example
Generic Class with two parameters
For example
Generic Method
Generic Interface
an interface is defined using generic type parameter
Syntax
interface interface-name<T>
{
void method-name(T t); // public abstract method.
}
class class-name<T> implements interface-name<T>
{
public void method-name(T t)
{ // code
}
}
Generic Interface
Example
public interface A <T> {
public void display(T t);
}
Source: javatpoint
Collection Framework
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
and deletion.
Java Collection means a single unit of objects.
Java Collection framework provides many interfaces
and classes
Interfaces - Set, List, Queue, Deque
Classes - ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet.
Source: javatpoint
What is Collection in Java
A Collection represents a single unit of objects, i.e., a
group.
What is a framework in Java
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
What is Collection framework
The Collection framework represents a unified
architecture for storing and manipulating a group of
objects. It has:
Interfaces and its implementations, i.e., classes
Source: javatpoint
Iterable Interface
The Iterable interface is the root interface for all the
collection classes.
The Collection interface extends the Iterable interface
and therefore all the subclasses of Collection interface
also implement the Iterable interface.
Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
Collection interface is implemented by all the classes
in the collection framework.
It declares the methods that every collection will have.
The Collection interface builds the foundation on
which the collection framework depends.
Some of the methods of Collection interface are
Boolean add ( Object obj),
void clear(), etc.
which are implemented by all the subclasses of
Collection interface.
Collection Interface
Common Methods on Collections
add()
remove()
get()
size()
isEmpty()
Contains()
Clear()
List Interface
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.
List Interface
To instantiate the List interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
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.
Iterator Interface
provides the facility of iterating the elements in a
forward direction only
N Method Description
o.
1 Public boolean It returns true if the iterator has more elements
hasNext() otherwise it returns false.
2 public Object next() It returns the element and moves the cursor
pointer to the next element.
3 public void remove() It removes the last elements returned by the
iterator. It is less used.
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.
ArrayList Class
implements the List interface
ArrayList – add() method
ArrayList – add() - specified position
ArrayList – remove()
ArrayList – isempty()
ArrayList - Contains(searching)
Example
LinkedList
LinkedList implements the Collection interface.
It uses a doubly linked list internally to store the
elements.
It allows duplicate elements.
It maintains the insertion order and not synchronized.
In LinkedList, the manipulation is fast because no
shifting is required.
LinkedList
LinkedList
It implements Deque Interface
addFirst() or offerFirst()
addLast() or offerLast()
getFirst( ) or peekFirst( ).
getLast( ) or peekLast( )
removeFirst( ) or pollFirst( ).
removeLast( ) or pollLast( ).
Vector
Vector uses a dynamic array to store the data elements.
It is similar to ArrayList.
However, It is synchronized.
Example
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){ Output:
System.out.println(itr.next());
} Ayush
} Amit
} Ashish
Garima
Vector
addElement()
firstElement()
lastElement()
insertElementAt(E element,int index)
capacity() – 10 by default
removeElement(Object element)
removeElementAt(int index)
elementAt(int index)
ArrayList vs LinkedList vs Vector
ArrayList LinkedList Vector
Storage dynamic array to doubly linked dynamic array to store
store the list to store the the elements.
elements. elements
Insertion Order It maintains It maintains
Synchronized No No Yes
Duplicate It allows It allows It allows
elements
Manipulation Slow since Fast, uses a Fast,compared to
speed shifting is doubly linked list ArrayList
required internally
Benefit Better for storing Better for Better for storing and
and accessing manipulation accessing data
data
Random access Yes No yes
Stack
The stack is the subclass of Vector.
It implements the last-in-first-out data structure, i.e.,
Stack.
The stack contains all of the methods of Vector class
and also provides its methods like
push()
pop()
peek() – returns top object but does not remove
empty()
search(Object element) – returns
Example
import java.util.*;
public class TestJavaCollection4{
public static void main(String
args[]){ Output:
Stack<String> stack = new
Stack<String>(); Ayush
stack.push("Ayush"); Garvit
stack.push("Garvit");
Amit
stack.push("Amit");
stack.push("Ashish"); Ashish
stack.push("Garima");
stack.pop();
Iterator<String>
itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Queue Interface
Queue interface maintains the first-in-first-out order.
It can be defined as an ordered list that is used to hold
the elements which are about to be processed.
There are various classes like PriorityQueue, Deque
which implements the Queue interface.