SlideShare a Scribd company logo
Java Class 5
“Once a Programmer always a Programmer.”
•Collection Framework in Java
•Generics
•Input-Output in Java
•Serialization
•Inner Classes
Java Values 2
Collection Framework in Java
Java Values 3
Collections in Java
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).
Its come in java.util package.
Hierarchy of Collection Framework
Java Values 4
Methods of Collection interface
Java Values 5
And many more…
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.
To instantiate the List interface
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
Example: List <String> list = new ArrayList();
Java Values 6
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.
Java Values 7
Array List Example
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java Values 8
Output?
LinkedList
Java Values 9
•LinkedList implements the Collection interface.
•It uses a doubly linked list internally to store the
elements.
•It can store the duplicate elements.
•It maintains the insertion order and is not synchronized.
•In LinkedList, the manipulation is fast because no
shifting is required.
Example
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java Values 10
Vector - Stack
Vector uses a dynamic array to store the data elements.
It is similar to ArrayList.
It’s a legacy class . Why it is legacy class?
However, It is synchronized and contains many methods that
are not the part of Collection framework.
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 boolean push(), boolean peek(),
boolean push(object o), which defines its properties.
Java Values 11
Example
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java Values 12
Output??
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, and ArrayDeque which implements the
Queue interface.
Java Values 13
Priority Queue
The PriorityQueue class implements the Queue interface.
It holds the elements or objects which are to be processed
by their priorities.
PriorityQueue doesn't allow null values to be stored in the
queue.
Deque:
Deque interface extends the Queue interface.
 In Deque, we can remove and add the elements from both
the side.
Deque stands for a double-ended queue which enables us
to perform the operations at both the ends.
ArrayDeque
ArrayDeque class implements the Deque interface.
It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements
from both the ends.
ArrayDeque is faster than ArrayList and Stack and
has no capacity restrictions.
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
for (String str : deque) { //Traversing elements
System.out.println(str);
}
}
Java Values 15
Output?
Set Interface
 Set Interface in Java is present in java.util package.
 It extends the Collection interface.
 It represents the unordered set of elements which
doesn't allow us to store the duplicate items.
 We can store at most one null value in Set.
 Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
Java Values 16
HashSet class implements Set Interface.
It represents the collection that uses a hash table for storage.
Hashing is used to store the elements in the HashSet.
It contains unique items.
LinkedHashSet class represents the LinkedList implementation
of Set Interface.
It extends the HashSet class and implements Set interface.
Like HashSet, It also contains unique elements.
It maintains the insertion order and permits null elements.
SortedSet is the alternate of Set interface that provides a total
ordering on its elements.
The elements of the SortedSet are arranged in the increasing
(ascending) order.
The SortedSet provides the additional methods that inhibit the
natural ordering of the elements.
Java Values 17
Java TreeSet class implements the Set interface that uses a
tree for storage.
Like HashSet, TreeSet also contains unique elements.
However, the access and retrieval time of TreeSet is quite fast.
The elements in TreeSet stored in ascending order.
public void setexample(){
// same way we can used HashSet()<>, LinkedHashSet()<>
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
Java Values 18
Java Map Interface
A map contains values on the basis of key, i.e. key-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.
Java Values 19
Java Values 20
Class Description
HashMap HashMap is the implementation
of Map, but it doesn't maintain
any order.
LinkedHashMap LinkedHashMap is the
implementation of Map. It
inherits HashMap class. It
maintains insertion order.
TreeMap TreeMap is the implementation
of Map and SortedMap. It
maintains ascending order.
•A Map doesn't allow duplicate keys, but you can have duplicate
values.
•A Map can't be traversed, so you need to convert it into Set
using keySet() or entrySet() method.
Method Description
V put(Object key, Object value) It is used to insert an entry in the
map.
void putAll(Map map) It is used to insert the specified map
in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the
specified key in the map only if it is
not already specified.
V remove(Object key) It is used to delete an entry for the
specified key.
boolean remove(Object key, Object
value)
It removes the specified values with
the associated specified keys from the
map.
Set keySet() It returns the Set view containing all
the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all
the keys and values.
Java Values 21
Example of Map
Public void MapExample(){
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
} Java Values 22
Output?
Java Values 23
Java Values 24
Sorting collections using utility methods
Example :Collections.sort();
equals () and hash Code contract in Java collections
object value and there reference
Overriding equals and hash Code methods in Java.
To get the value which is save in hashmap or tree
map.
hashCode()
It returns the hashcode value as an Integer.
Hashcode value is mostly used in hashing based
collections like HashMap, HashSet,
HashTable….etc. This method must be overridden in
every class which overrides equals() method.
Java Values 25
Java Values 26
Java Values 27
Java Values.com
•The Java Generics programming is introduced in J2SE
5 to deal with type-safe objects.
•It makes the code stable by detecting the bugs at
compile time.
•Before generics, we can store any type of objects in the
collection, i.e., non-generic.
•Now generics force the java programmer to store a
specific type of objects.
•There are mainly 3 advantages of generics. They are as
follows:
1. Type-safety
2. Type casting is not required
3. Compile-Time Checking
Wildcard in Java Generics
Java Values 28
•The ? (question mark) symbol represents the wildcard
element. It means any type.
•If we write <? extends Number>, it means any child
class of Number, e.g., Integer, Float, and double.
•Now we can call the method of Number class through
any child class object.
•We can use a wildcard as a type of a parameter, field,
return type, or local variable.
•However, it is not allowed to use a wildcard as a
type argument for a generic method invocation, a
generic class instance creation, or a supertype.
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);
}
}
Java Values 29
Output?
Serialization and Deserialization
Serialization in Java is a mechanism of writing the state of
an object into a byte-stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS
technologies.
The reverse operation of serialization is
called deserialization where byte-stream is converted into
an object.
The serialization and deserialization process is platform-
independent, it means you can serialize an object in a
platform and deserialize in different platform.
For serializing the object, we call
the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method
of ObjectInputStream class.
Java Values 30
Workflow
Java Values 31
Java Values 32
import java.io.*;
class Persist{
public static void main(String args[]){
try{
Student s1 =new Student(211,"ravi"); //Creating the object
FileOutputStream fout=new FileOutputStream("f.txt"); //Creating stream and writing the object
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush(); //closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Output?
Java Values 33
import java.io.*;
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Output?
Inner Classes
Inner Classes
Local Classes
Anonymous Classes
Static Nested Classes
Java Values 34
Type Description
Member Inner Class A class created within class and
outside method.
Anonymous Inner Class A class created for implementing
interface or extending class. Its name
is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or
interface.
Java Values 35
Inner class is a part of nested class. Non-static nested
classes are known as inner classes.
Advantage of java inner classes
There are basically three advantages of inner
classes in java. They are as follows:
1) Nested classes represent a special type of
relationship that is it can access all the members
(data members and methods) of outer
class including private.
2) Nested classes are used to develop more
readable and maintainable code because it
logically group classes and interfaces in one place
only.
3) Code Optimization: It requires less code to
write.
Java Values 36
JAVA Input Output
The Stream is a sequence of Bytes.
Output Stream: Writing Data to a Stream.
Input Stream: Reading Data from a Stream.
If a stream has a buffer in memory then it is
Buffered Stream.
Character stream have character data and
are used for storing and retrieving the text.
Java Values 37
Java Values 38
There are four types of abstract Streams
class
1. Reader: Read Character
2. Writer: Write Character
3. InputStream: A stream to read binary data.
4. OutputStream: A Stream to write binary data.
Generally we are using BufferedInputStream,
BufferedOutputStream, BufferedReader and
BufferedWriter for better performance of
Buffered I/O Classes.
Java Values 39
Byte Stream Classes
Java Values 40
Character Stream I/O Classes
Java Values 41
InputStream
Used to read binary data.
FileInputStream enables easy reading from a
file.
BufferInputStream provides data buffering .
InputStream class has three read method overloads.
1. public abstract int read(int b1)
2. public int read(byte[] data)
3. public int read(byte[] data, int offset, int length)
Where the offset stands for the first bytes should be
placed.
Java Values 42
The Predefined Streams
Java programs automatically import the java.lang package.
This package defines a class calledSystem, which
encapsulates several aspects of the run-time environment.
System also contains three predefined stream variables: in,
out, and err.
These fields are declared as public, static, and final within
System. This means that they can be used by any other part
of your program and without reference to a specific System
object.
System.in is an object of type InputStream;
System.out and System.err are objects of type
PrintStream. These are byte streams, even though they
typically are used to read and write characters from and to the
console. Java Values 43
File
File object is used to obtain or manipulate the information
associated with a disk file such as permission, time, date
and directory path.
File object can refer to either file or directory.
File f1 = new File(“mcaii.txt”);
File f1 = new File(“c:mcaii.txt”);
Files are stored in binary form.
The following constructors can be used to create
File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Java Values 44
FileInputStream
The FileInputStream class creates an InputStream that you can
use to read bytes from a file.
Its two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObj)
FileOutputStream
FileOutputStream creates an OutputStream that you can use to
write bytes to a file.
Its most commonly used constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
Java Values 45
The PrintWriter Class
PrintWriter is one of the character-based classes.
Using a character-based class for console output makes it
easier to internationalize your program.
PrintWriter defines several constructors. The one we will
use is shown here:
PrintWriter(OutputStream outputStream, boolean
flushOnNewline)
Here, outputStream is an object of type OutputStream, and
flushOnNewline controls whether Java flushes the output
stream every time a println( ) method is called.
PrintWriter supports the print( ) and println( ) methods
for all types including Object.
Java Values 46
 The following application illustrates using a PrintWriter to
handle console output
// Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo
{
public static void main(String args[])
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
Java Values 47
Reading and Writing Files
Two of the most often-used stream classes are
FileInputStream and FileOutputStream, which create byte
streams linked to files.
To open a file, you simply create an object of one of these
classes, specifying the name of the file as an argument to the
constructor.
The following are the forms that we will be using:
 FileInputStream(String fileName) throws FileNotFoundException
 FileOutputStream(String fileName) throws FileNotFoundException
DataOutputStream and DataInputStream
DataOutputStream and DataInputStream enable you to write
or read primitive data to or from a stream.
They implement the DataOutput and DataInput interfaces,
respectively.
Java Values 48
Summary
Collection Framework in Java
 The Collections Framework - Set Interface- List Interface - Map Interface -
Queue Interface -Sorting collections using utility methods
 equals () and hash Code contract in Java collections
 Overriding equals and hash Code methods in Java
Generics
 Generics for Collections, class and methods
Input-Output in Java
 What is a stream? ,Bytes vs. Characters, Java IO API ,Reading a file;
writing to a file using various APIs
 Reading User input from console , PrintWriter Class
Serialization
 Object Serialization , Serializable Interface , De-Serializable
Inner Classes
 Inner Classes ,Member Classes, Local Classes, Anonymous Classes,
Static Nested Classes
Java Values 49
Java Values 50
Thank you !!!
If you like my training session please feel free to give
me star in my git-hub account !!!
https://github.com/eewsagar

More Related Content

What's hot (20)

Static Members-Java.pptx
Static Members-Java.pptxStatic Members-Java.pptx
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
Ravindra Rathore
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Pooja Talreja
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Java collection
Java collectionJava collection
Java collection
Arati Gadgil
 
Spring GraphQL
Spring GraphQLSpring GraphQL
Spring GraphQL
VMware Tanzu
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
Ravindra Rathore
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Pooja Talreja
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Java collection
Java collectionJava collection
Java collection
Arati Gadgil
 
Spring GraphQL
Spring GraphQLSpring GraphQL
Spring GraphQL
VMware Tanzu
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 

Similar to Collection Framework in Java | Generics | Input-Output in Java | Serialization | Inner Classes | Java class 4 (20)

collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
Java Collections
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
Dr. SURBHI SAROHA
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Java.util
Java.utilJava.util
Java.util
Ramakrishna kapa
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
Ravi Chythanya
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
Rakesh Madugula
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Javasession7
Javasession7Javasession7
Javasession7
Rajeev Kumar
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Java Collection Interview Questions [Updated]
Java Collection Interview Questions [Updated]Java Collection Interview Questions [Updated]
Java Collection Interview Questions [Updated]
SoniaMathias2
 
Collections
CollectionsCollections
Collections
Rajkattamuri
 
Module-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptxModule-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptx
rekhakeerti19
 
Java Collection slide ppt presentation..
Java Collection slide ppt presentation..Java Collection slide ppt presentation..
Java Collection slide ppt presentation..
madduriradha
 
Java util
Java utilJava util
Java util
Srikrishna k
 
java unit 4 pdf - about java collections
java unit 4 pdf - about java collectionsjava unit 4 pdf - about java collections
java unit 4 pdf - about java collections
aapalaks
 
Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
LJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptxLJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptx
Raneez2
 
Java 103
Java 103Java 103
Java 103
Manuela Grindei
 
collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
Ravi Chythanya
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
Rakesh Madugula
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Javasession7
Javasession7Javasession7
Javasession7
Rajeev Kumar
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Java Collection Interview Questions [Updated]
Java Collection Interview Questions [Updated]Java Collection Interview Questions [Updated]
Java Collection Interview Questions [Updated]
SoniaMathias2
 
Module-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptxModule-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptx
rekhakeerti19
 
Java Collection slide ppt presentation..
Java Collection slide ppt presentation..Java Collection slide ppt presentation..
Java Collection slide ppt presentation..
madduriradha
 
java unit 4 pdf - about java collections
java unit 4 pdf - about java collectionsjava unit 4 pdf - about java collections
java unit 4 pdf - about java collections
aapalaks
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
LJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptxLJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptx
Raneez2
 
Ad

More from Sagar Verma (10)

Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Java introduction
Java introductionJava introduction
Java introduction
Sagar Verma
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
Sagar Verma
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introduction
Sagar Verma
 
2015-16 software project list
2015-16 software project list2015-16 software project list
2015-16 software project list
Sagar Verma
 
Ns2 new project list
Ns2 new project listNs2 new project list
Ns2 new project list
Sagar Verma
 
Privacy preserving dm_ppt
Privacy preserving dm_pptPrivacy preserving dm_ppt
Privacy preserving dm_ppt
Sagar Verma
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Java introduction
Java introductionJava introduction
Java introduction
Sagar Verma
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
Sagar Verma
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introduction
Sagar Verma
 
2015-16 software project list
2015-16 software project list2015-16 software project list
2015-16 software project list
Sagar Verma
 
Ns2 new project list
Ns2 new project listNs2 new project list
Ns2 new project list
Sagar Verma
 
Privacy preserving dm_ppt
Privacy preserving dm_pptPrivacy preserving dm_ppt
Privacy preserving dm_ppt
Sagar Verma
 
Ad

Recently uploaded (20)

362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 

Collection Framework in Java | Generics | Input-Output in Java | Serialization | Inner Classes | Java class 4

  • 1. Java Class 5 “Once a Programmer always a Programmer.” •Collection Framework in Java •Generics •Input-Output in Java •Serialization •Inner Classes
  • 2. Java Values 2 Collection Framework in Java
  • 3. Java Values 3 Collections in Java 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). Its come in java.util package.
  • 4. Hierarchy of Collection Framework Java Values 4
  • 5. Methods of Collection interface Java Values 5 And many more…
  • 6. 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. To instantiate the List interface List <data-type> list1= new ArrayList(); List <data-type> list2 = new LinkedList(); List <data-type> list3 = new Vector(); List <data-type> list4 = new Stack(); Example: List <String> list = new ArrayList(); Java Values 6
  • 7. 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. Java Values 7
  • 8. Array List Example import java.util.*; class TestJavaCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Ravi");//Adding object in arraylist list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Java Values 8 Output?
  • 9. LinkedList Java Values 9 •LinkedList implements the Collection interface. •It uses a doubly linked list internally to store the elements. •It can store the duplicate elements. •It maintains the insertion order and is not synchronized. •In LinkedList, the manipulation is fast because no shifting is required.
  • 10. Example import java.util.*; public class TestJavaCollection2{ public static void main(String args[]){ LinkedList<String> al=new LinkedList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Java Values 10
  • 11. Vector - Stack Vector uses a dynamic array to store the data elements. It is similar to ArrayList. It’s a legacy class . Why it is legacy class? However, It is synchronized and contains many methods that are not the part of Collection framework. 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 boolean push(), boolean peek(), boolean push(object o), which defines its properties. Java Values 11
  • 12. Example import java.util.*; public class TestJavaCollection4{ public static void main(String args[]){ Stack<String> stack = new Stack<String>(); stack.push("Ayush"); stack.push("Garvit"); stack.push("Amit"); stack.push("Ashish"); stack.push("Garima"); stack.pop(); Iterator<String> itr=stack.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Java Values 12 Output??
  • 13. 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, and ArrayDeque which implements the Queue interface. Java Values 13
  • 14. Priority Queue The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue. Deque: Deque interface extends the Queue interface.  In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.
  • 15. ArrayDeque ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends. ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions. Deque<String> deque = new ArrayDeque<String>(); deque.add("Gautam"); deque.add("Karan"); deque.add("Ajay"); for (String str : deque) { //Traversing elements System.out.println(str); } } Java Values 15 Output?
  • 16. Set Interface  Set Interface in Java is present in java.util package.  It extends the Collection interface.  It represents the unordered set of elements which doesn't allow us to store the duplicate items.  We can store at most one null value in Set.  Set is implemented by HashSet, LinkedHashSet, and TreeSet. Java Values 16
  • 17. HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items. LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements. SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional methods that inhibit the natural ordering of the elements. Java Values 17
  • 18. Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order. public void setexample(){ // same way we can used HashSet()<>, LinkedHashSet()<> TreeSet<String> set=new TreeSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); //traversing elements Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } Java Values 18
  • 19. Java Map Interface A map contains values on the basis of key, i.e. key-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. Java Values 19
  • 20. Java Values 20 Class Description HashMap HashMap is the implementation of Map, but it doesn't maintain any order. LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order. TreeMap TreeMap is the implementation of Map and SortedMap. It maintains ascending order. •A Map doesn't allow duplicate keys, but you can have duplicate values. •A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
  • 21. Method Description V put(Object key, Object value) It is used to insert an entry in the map. void putAll(Map map) It is used to insert the specified map in the map. V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only if it is not already specified. V remove(Object key) It is used to delete an entry for the specified key. boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the map. Set keySet() It returns the Set view containing all the keys. Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and values. Java Values 21
  • 22. Example of Map Public void MapExample(){ Map map=new HashMap(); //Adding elements to map map.put(1,"Amit"); map.put(5,"Rahul"); map.put(2,"Jai"); map.put(6,"Amit"); //Traversing Map Set set=map.entrySet();//Converting to Set so that we can traverse Iterator itr=set.iterator(); while(itr.hasNext()){ //Converting to Map.Entry so that we can get key and value separately Map.Entry entry=(Map.Entry)itr.next(); System.out.println(entry.getKey()+" "+entry.getValue()); } Java Values 22 Output?
  • 25. Sorting collections using utility methods Example :Collections.sort(); equals () and hash Code contract in Java collections object value and there reference Overriding equals and hash Code methods in Java. To get the value which is save in hashmap or tree map. hashCode() It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing based collections like HashMap, HashSet, HashTable….etc. This method must be overridden in every class which overrides equals() method. Java Values 25
  • 27. Java Values 27 Java Values.com •The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. •It makes the code stable by detecting the bugs at compile time. •Before generics, we can store any type of objects in the collection, i.e., non-generic. •Now generics force the java programmer to store a specific type of objects. •There are mainly 3 advantages of generics. They are as follows: 1. Type-safety 2. Type casting is not required 3. Compile-Time Checking
  • 28. Wildcard in Java Generics Java Values 28 •The ? (question mark) symbol represents the wildcard element. It means any type. •If we write <? extends Number>, it means any child class of Number, e.g., Integer, Float, and double. •Now we can call the method of Number class through any child class object. •We can use a wildcard as a type of a parameter, field, return type, or local variable. •However, it is not allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
  • 29. 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); } } Java Values 29 Output?
  • 30. Serialization and Deserialization Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform- independent, it means you can serialize an object in a platform and deserialize in different platform. For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization we call the readObject() method of ObjectInputStream class. Java Values 30
  • 32. Java Values 32 import java.io.*; class Persist{ public static void main(String args[]){ try{ Student s1 =new Student(211,"ravi"); //Creating the object FileOutputStream fout=new FileOutputStream("f.txt"); //Creating stream and writing the object ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(s1); out.flush(); //closing the stream out.close(); System.out.println("success"); }catch(Exception e){System.out.println(e);} } } import java.io.Serializable; public class Student implements Serializable{ int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } } Output?
  • 33. Java Values 33 import java.io.*; class Depersist{ public static void main(String args[]){ try{ //Creating stream to read the object ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt")); Student s=(Student)in.readObject(); //printing the data of the serialized object System.out.println(s.id+" "+s.name); //closing the stream in.close(); }catch(Exception e){System.out.println(e);} } } import java.io.Serializable; public class Student implements Serializable{ int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } } Output?
  • 34. Inner Classes Inner Classes Local Classes Anonymous Classes Static Nested Classes Java Values 34
  • 35. Type Description Member Inner Class A class created within class and outside method. Anonymous Inner Class A class created for implementing interface or extending class. Its name is decided by the java compiler. Local Inner Class A class created within method. Static Nested Class A static class created within class. Nested Interface An interface created within class or interface. Java Values 35 Inner class is a part of nested class. Non-static nested classes are known as inner classes.
  • 36. Advantage of java inner classes There are basically three advantages of inner classes in java. They are as follows: 1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. 2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. 3) Code Optimization: It requires less code to write. Java Values 36
  • 37. JAVA Input Output The Stream is a sequence of Bytes. Output Stream: Writing Data to a Stream. Input Stream: Reading Data from a Stream. If a stream has a buffer in memory then it is Buffered Stream. Character stream have character data and are used for storing and retrieving the text. Java Values 37
  • 39. There are four types of abstract Streams class 1. Reader: Read Character 2. Writer: Write Character 3. InputStream: A stream to read binary data. 4. OutputStream: A Stream to write binary data. Generally we are using BufferedInputStream, BufferedOutputStream, BufferedReader and BufferedWriter for better performance of Buffered I/O Classes. Java Values 39
  • 41. Character Stream I/O Classes Java Values 41
  • 42. InputStream Used to read binary data. FileInputStream enables easy reading from a file. BufferInputStream provides data buffering . InputStream class has three read method overloads. 1. public abstract int read(int b1) 2. public int read(byte[] data) 3. public int read(byte[] data, int offset, int length) Where the offset stands for the first bytes should be placed. Java Values 42
  • 43. The Predefined Streams Java programs automatically import the java.lang package. This package defines a class calledSystem, which encapsulates several aspects of the run-time environment. System also contains three predefined stream variables: in, out, and err. These fields are declared as public, static, and final within System. This means that they can be used by any other part of your program and without reference to a specific System object. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console. Java Values 43
  • 44. File File object is used to obtain or manipulate the information associated with a disk file such as permission, time, date and directory path. File object can refer to either file or directory. File f1 = new File(“mcaii.txt”); File f1 = new File(“c:mcaii.txt”); Files are stored in binary form. The following constructors can be used to create File objects: File(String directoryPath) File(String directoryPath, String filename) File(File dirObj, String filename) File(URI uriObj) Java Values 44
  • 45. FileInputStream The FileInputStream class creates an InputStream that you can use to read bytes from a file. Its two most common constructors are shown here: FileInputStream(String filepath) FileInputStream(File fileObj) FileOutputStream FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used constructors are shown here: FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append) Java Values 45
  • 46. The PrintWriter Class PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize your program. PrintWriter defines several constructors. The one we will use is shown here: PrintWriter(OutputStream outputStream, boolean flushOnNewline) Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. PrintWriter supports the print( ) and println( ) methods for all types including Object. Java Values 46
  • 47.  The following application illustrates using a PrintWriter to handle console output // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } } Java Values 47
  • 48. Reading and Writing Files Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. The following are the forms that we will be using:  FileInputStream(String fileName) throws FileNotFoundException  FileOutputStream(String fileName) throws FileNotFoundException DataOutputStream and DataInputStream DataOutputStream and DataInputStream enable you to write or read primitive data to or from a stream. They implement the DataOutput and DataInput interfaces, respectively. Java Values 48
  • 49. Summary Collection Framework in Java  The Collections Framework - Set Interface- List Interface - Map Interface - Queue Interface -Sorting collections using utility methods  equals () and hash Code contract in Java collections  Overriding equals and hash Code methods in Java Generics  Generics for Collections, class and methods Input-Output in Java  What is a stream? ,Bytes vs. Characters, Java IO API ,Reading a file; writing to a file using various APIs  Reading User input from console , PrintWriter Class Serialization  Object Serialization , Serializable Interface , De-Serializable Inner Classes  Inner Classes ,Member Classes, Local Classes, Anonymous Classes, Static Nested Classes Java Values 49
  • 50. Java Values 50 Thank you !!! If you like my training session please feel free to give me star in my git-hub account !!! https://github.com/eewsagar