Unit 3&unit 4 Notes Oosj
Unit 3&unit 4 Notes Oosj
text1.equals(text2) // true
// ORIGINAL
RECORDS:
Example 1
// Main class
class GFG {
System.out.println(e1.toString());
Output:
EXAMPLE 2:
// Main class
class GFG {
System.out.println(e1.toString());
e2.getFullName();
+ e2.generateEmployeeToken());
+ e1.equals(e2));
Output:
Seren
Example
sealed class Human permits Manish, Vartika, Anjali
System.out.println("Default");
System.out.println("Manish Sharma");
System.out.println("Vartika Dadheech");
{
System.out.println("Anjali Sharma");
Human is the parent class of Manish, Vartika, and Anjali. It is a sealed class so; other classes
cannot inherit it.
Manish, Vartika, and Anjali are child classes of the Human class, and it is necessary to make
them either sealed, non-sealed, or final. Child classes of a sealed class must be sealed, non-
sealed, or final.
If any class other than Manish, Vartika, and Anjali tries to inherit from the Human class, it
will cause a compiler error.
EXAMPLE:
import java.lang.*;
System.out.println("Default");
System.out.println("Manish Sharma");
}
}
System.out.println("Vartika Dadheech");
System.out.println("Anjali Sharma");
h2.printName();
h3.printName();
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java
Collection of Objects. In Java, a separate framework named the “Collection Framework” has
been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it.
In Java, the Collection interface (java.util.Collection) and Map interface (java.util.Map) are the
two main “root” interfaces of Java collection classes.
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 Collection in Java
It is optional.
The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
Algorithm
Since the lack of a collection framework gave rise to the above set of disadvantages, the
following are the advantages of the collection framework.
1. Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map,
all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have
some common set of methods.
2. Reduces programming effort: A programmer doesn’t have to worry about the design of
the Collection but rather he can focus on its best use in his program. Therefore, the basic
concept of Object-oriented programming (i.e.) abstraction has been successfully
implemented.
The utility package, (java.util) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable
interface which provides the iterator to iterate through all the collections. This interface is
extended by the main collection interface which acts as a root for the collection framework. All
the collections extend this collection interface thereby extending the properties of the iterator and
the methods of this interface. The following figure illustrates the hierarchy of the collection
framework.
Before understanding the different components in the above framework, let’s first understand a
class and an interface.
Class: A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, nobody).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
What is a Framework in Java?
A framework is a set of classes and interfaces which provide a ready-made architecture. In order
to implement a new feature or a class, there is no need to define a framework. However, an
optimal object-oriented design always includes a framework with a collection of classes such
that all the classes perform the same kind of task.
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these
collections had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no
correlation among them. And also, it is very difficult for the users to remember all the different
methods, syntax, and constructors present in every collection class.
Let’s understand this with an example of adding an element in a hashtable and a vector.
Example:
class CollectionDemo {
The collection framework contains multiple interfaces where every interface is used to store a
specific type of data. The following are the interfaces present in the framework.
1. Iterable Interface
This is the root interface for the entire collection framework. The collection interface extends the
iterable interface. Therefore, inherently, all the interfaces and classes implement this interface.
The main functionality of this interface is to provide an iterator for the collections. Therefore,
this interface contains only one abstract method which is the iterator. It returns the
Iterator iterator();
2. Collection Interface
This interface extends the iterable interface and is implemented by all the classes in the
collection framework. This interface contains all the basic methods which every collection has
like adding the data into the collection, removing the data, clearing the data, etc. All these
methods are implemented in this interface because these methods are implemented by all the
classes irrespective of their style of implementation. And also, having these methods in this
interface ensures that the names of the methods are universal for all the collections. Therefore, in
short, we can say that this interface builds a foundation on which the collection classes are
implemented.
3. List Interface
This is a child interface of the collection interface. This interface is dedicated to the data of the
list type in which we can store all the ordered collections of the objects. This also allows
duplicate data to be present in it. This list interface is implemented by various classes like
ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list
object with any of these classes.
For example:
i). ArrayList
ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard
arrays but can be helpful in programs where lots of manipulation in the array is needed. The size
of an ArrayList is increased automatically if the collection grows or shrinks if the objects are
removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can
not be used for primitive types, like int, char, etc. We will need a wrapper class for such cases.
// working of ArrayList
import java.io.*;
import java.util.*;
class GFG {
// Main Method
{
// Declaring the ArrayList with
// initial size n
ArrayList<Integer> al = new
ArrayList<Integer>();
al.add(i);
// Printing elements
System.out.println(al);
al.remove(3);
// after deletion
System.out.println(al);
}
}
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
ii). LinkedList
The LinkedList class is an implementation of the LinkedList data structure which is a linear data
structure where the elements are not stored in contiguous locations and every element is a
separate object with a data part and address part. The elements are linked using pointers and
addresses. Each element is known as a node.
// working of LinkedList
import java.io.*;
import java.util.*;
class GFG {
// Main Method
LinkedList<Integer> ll = new
LinkedList<Integer>();
// Appending new elements at
ll.add(i);
// Printing elements
System.out.println(ll);
ll.remove(3);
// after deletion
System.out.println(ll);
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
iii). Vector
A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. This is identical
to ArrayList in terms of implementation. However, the primary difference between a vector and
an ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.
// working of Vector
import java.io.*;
import java.util.*;
class GFG {
// Main Method
v.add(i);
// Printing elements
System.out.println(v);
v.remove(3);
// after deletion
System.out.println(v);
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
iv). Stack
Stack class models and implements the Stack data structure. The class is based on the basic
principle of last-in-first-out. In addition to the basic push and pop operations, the class provides
three more functions empty, search, and peek. The class can also be referred to as the subclass of
Vector.
Let’s understand the stack with an example:
// working of a stack
import java.util.*;
// Main Method
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");
stack.push("Geeks");
while (itr.hasNext()) {
System.out.println();
stack.pop();
itr = stack.iterator();
while (itr.hasNext()) {
Output
Note: Stack is a subclass of Vector and a legacy class. It is thread-safe which might be overhead
in an environment where thread safety is not needed. An alternate to Stack is to use
ArrayDequeue which is not thread-safe and has faster array implementation.
4. Queue Interface
As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a
real-world queue line. This interface is dedicated to storing all the elements where the order of
the elements matter. For example, whenever we try to book a ticket, the tickets are sold on a first
come first serve basis. Therefore, the person whose request arrives first into the queue gets the
ticket. There are various classes like PriorityQueue, ArrayDeque, etc. Since all these subclasses
implement the queue, we can instantiate a queue object with any of these classes.
For example:
The most frequently used implementation of the queue interface is the PriorityQueue.
Priority Queue
A PriorityQueue is used when the objects are supposed to be processed based on priority. It is
known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the
queue are needed to be processed according to the priority and this class is used in these cases.
The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered
according to the natural ordering, or by a Comparator provided at queue construction time,
depending on which constructor is used.
import java.util.*;
class GfG {
// Main Method
pQueue.add(20);
pQueue.add(15);
System.out.println(pQueue.peek());
System.out.println(pQueue.poll());
System.out.println(pQueue.peek());
Output
10
10
15
5. Deque Interface
This is a very slight variation of the queue data structure. Deque, also known as a double-ended
queue, is a data structure where we can add and remove elements from both ends of the queue.
This interface extends the queue interface. The class which implements this interface is
ArrayDeque. Since ArrayDeque class implements the Deque interface, we can instantiate a
deque object with this class.
For example:
ArrayDeque
ArrayDeque class which is implemented in the collection framework provides us with a way to
apply resizable array. This is a special kind of array that grows and allows users to add or
remove an element from both sides of the queue. Array deques have no capacity restrictions and
they grow as necessary to support usage. Let’s understand ArrayDeque with an example:
// Java program to demonstrate the ArrayDeque class in Java
import java.util.*;
{ // Initializing an deque
de_que.add(10);
de_que.add(20);
de_que.add(30);
de_que.add(40);
de_que.add(50);
System.out.println(de_que);
// clear() method
de_que.clear();
de_que.addFirst(564);
de_que.addFirst(291);
de_que.addLast(24);
de_que.addLast(14);
System.out.println(de_que);
}}
Output
6. Set Interface
A set is an unordered collection of objects in which duplicate values cannot be stored. This
collection is used when we wish to avoid the duplication of the objects and wish to store only the
unique objects. This set interface is implemented by various classes like HashSet, TreeSet,
LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object
with any of these classes. For example:
i). HashSet
The HashSet class is an inherent implementation of the hash table data structure. The objects that
we insert into the HashSet do not guarantee to be inserted in the same order. The objects are
inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s
understand HashSet with an example:
import java.util.*;
hs.add("Geeks");
hs.add("For");
hs.add("Geeks");
hs.add("Is");
hs.add("Very helpful");
// Traversing elements
while (itr.hasNext()) {
System.out.println(itr.next());
} }}
Output
Very helpful
Geeks
For
Is
ii). LinkedHashSet
A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked
list to store the data and retains the ordering of the elements. Let’s understand the LinkedHashSet
with an example:
// working of a LinkedHashSet
import java.util.*;
// Main Method
LinkedHashSet<String> lhs
= new LinkedHashSet<String>();
lhs.add("Geeks");
lhs.add("For");
lhs.add("Geeks");
lhs.add("Is");
lhs.add("Very helpful");
// Traversing elements
while (itr.hasNext()) {
System.out.println(itr.next());
Output
Geeks
For
Is
Very helpful
This interface is very similar to the set interface. The only difference is that this interface has
extra methods that maintain the ordering of the elements. The sorted set interface extends the set
interface and is used to handle the data which needs to be sorted. The class which implements
this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a
SortedSet object with this class.
For example:
TreeSet
The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a set
using their natural ordering whether or not an explicit comparator is provided. This must be
consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a
Comparator provided at a set creation time, depending on which constructor is used.
import java.util.*;
ts.add("Geeks");
ts.add("For");
ts.add("Geeks");
ts.add("Is");
ts.add("Very helpful");
// Traversing elements
Iterator<String> itr = ts.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
} }}
Output
For
Geeks
Is
Very helpful
8. Map Interface
A map is a data structure that supports the key-value pair for mapping the data. This interface
doesn’t support duplicate keys because the same key cannot have multiple mappings; however, it
allows duplicate values in different keys. A map is useful if there is data and we wish to perform
operations on the basis of the key. This map interface is implemented by various classes like
HashMap, TreeMap, etc. Since all the subclasses implement the map, we can instantiate a map
object with any of these classes.
For example:
HashMap
HashMap provides the basic implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a
technique called Hashing. Hashing is a technique of converting a large String to a small String
that represents the same String so that the indexing and search operations are faster. HashSet also
uses HashMap internally. Let’s understand the HashMap with an example:
import java.util.*;
hm.put(1, "Geeks");
hm.put(2, "For");
hm.put(3, "Geeks");
}}
Output
LinkedHashMap in Java
The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an
order of elements inserted into it. HashMap provided the advantage of quick insertion, search,
and deletion but it never maintained the track and order of insertion, which the LinkedHashMap
provides where the elements can be accessed in their insertion order.
A LinkedHashMap contains values based on the key. It implements the Map interface
and extends the HashMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It is non-synchronized.
It is the same as HashMap with an additional feature that it maintains insertion order. For
example, when we run the code with a HashMap, we get a different order of elements.
Declaration:
Here, K is the key Object type and V is the value Object type
It implements Map<K, V> interface, and extends HashMap<K, V> class. Though the Hierarchy
of LinkedHashMap is as depicted in below media as follows:
A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.
Therefore, the class is declared as:
In this class, the data is stored in the form of nodes. The implementation of the LinkedHashMap
is very similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is
represented as:
Hash: All the input keys are converted into a hash which is a shorter form of the key so
that the search and insertion are faster.
Key: Since this class extends HashMap, the data is stored in the form of a key-value pair.
Therefore, this parameter is the key to the data.
Value: For every key, there is a value associated with it. This parameter stores the value
of the keys. Due to generics, this value can be of any form.
Next: Since the LinkedHashMap stores the insertion order, this contains the address to
the next node of the LinkedHashMap.
Previous: This parameter contains the address to the previous node of the
LinkedHashMap.
// LinkedHashMapExample
public class GFG {
Output
{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=www.geeksforgeeks.org}
Getting value for key 'one': practice.geeksforgeeks.org
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value 'practice.geeksforgeeks.org'? true
delete element 'one': practice.geeksforgeeks.org
Mappings of LinkedHashMap : {two=code.geeksforgeeks.org, four=www.geeksforgeeks.org}
Let’s see how to perform a few frequently used operations on the LinkedHashMap class
instance.
Operation 1: Adding Elements
In order to add an element to the LinkedHashMap, we can use the put() method. This is different
from HashMap because in HashMap, the insertion order is not retained but it is retained in the
LinkedHashMap.
Example
// Elements to a LinkedHashMap
import java.util.*;
// Main class
// AddElementsToLinkedHashMap
class GFG {
// Initialization of a LinkedHashMap
// using Generics
hm1.put(3, "Geeks");
hm1.put(2, "For");
hm1.put(1, "Geeks");
// Printing mappings to the console
+ hm1);
Output
After adding elements if we wish to change the element, it can be done by again adding the
element using the put() method. Since the elements in the LinkedHashMap are indexed using the
keys, the value of the key can be changed by simply re-inserting the updated value for the key
for which we wish to change.
Example
// of LinkedHashMap
import java.util.*;
// Main class
// UpdatingLinkedHashMap
class GFG {
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();
hm.put(3, "Geeks");
hm.put(2, "Geeks");
hm.put(1, "Geeks");
hm.put(2, "For");
Output
In order to remove an element from the LinkedHashMap, we can use the remove() method. This
method takes the value of key as input, searches for existence of such key and then removes the
mapping for the key from this LinkedHashMap if it is present in the map. Apart from that, we
can also remove the first entered element from the map if the maximum size is defined.
Example
// from LinkedHashMap
// Main class
// RemovingMappingsFromLinkedHashMap
class GFG {
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
hm.put(3, "Geeks");
hm.put(2, "Geeks");
hm.put(1, "Geeks");
hm.put(4, "For");
hm.remove(4);
}
Output
There are multiple ways to iterate through the LinkedHashMap. The most famous way is to use a
for-each loop over the set view of the map (fetched using map.entrySet() instance method). Then
for each entry (set element) the values of key and value can be fetched usingthe getKey() and the
getValue() method.
Example
import java.util.*;
// Main class
// IteratingOverLinkedHashMap
class GFG {
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
hm.put(3, "Geeks");
hm.put(2, "For");
hm.put(1, "Geeks");
hm.entrySet()) {
Output
3 : Geeks
2 : For
1 : Geeks
Hashtable in Java
The Hashtable class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value. To successfully store and retrieve objects from a
hashtable, the objects used as keys must implement the hashCode method and the equals
method.
import java.util.Enumeration;
import java.util.Hashtable;
Sorting in Java
Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort,
insertion sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use
any kind of algorithms. It is as simple sorting with the help of linear and non-linear data
structures present within java. So there is sorting done with the help of brute force in java
with the help of loops and there are two in-built methods to sort in Java.
Ways of sorting in Java
1. Using loops
2. Using sort() method of Arrays class
3. Using sort method of Collections class
4. Sorting on a subarray
5. // Java program to demonstrate working of Collections.sort()
6. import java.util.*;
7.
8. public class GFG {
9. public static void main(String[] args)
10. {
11. // Create a list of strings
12. ArrayList<String> al = new ArrayList<String>();
13. al.add("Geeks For Geeks");
14. al.add("Friends");
15. al.add("Dear");
16. al.add("Is");
17. al.add("Superb");
18.
19. /* Collections.sort method is sorting the
20. elements of ArrayList in ascending order. */
21. Collections.sort(al);
22.
23. // Let us print the sorted list
24. System.out.println("List after the use of"
25. + " Collection.sort() :\n" + al);
26. }
27. }
Comparable Interface
The Comparable interface is used to compare an object of the same class with an instance of
that class, it provides ordering of data for objects of the user-defined class. The class has to
implement the java.lang.Comparable interface to compare its instance, it provides the
compareTo method that takes a parameter of the object of that class. In this article, we will
see how we can sort an array of pairs of different data types on the different parameters of
comparison.
// Class 1
// A class to represent a Student
class Student {
// Attributes of a student
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address)
{
// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}
// Class 4
// Main class
class GFG {
Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc
Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur
Properties Class in Java
The Properties class represents a persistent set of properties. The Properties can be
saved to a stream or loaded from a stream. It belongs
to java.util package. Properties define the following instance variable. This variable
holds a default property list associated with a Properties object.
Features of Properties class:
Properties is a subclass of Hashtable.
It is used to maintain a list of values in which the key is a string and the value is also a
string i.e; it can be used to store and retrieve string type data from the properties file.
Properties class can specify other properties list as it’s the default. If a particular key
property is not present in the original Properties list, the default properties will be searched.
Properties object does not require external synchronization and Multiple threads can share a
single Properties object.
Also, it can be used to retrieve the properties of the system.
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
// create a reader object on the properties file
FileReader reader = new FileReader("db.properties");
// create properties object
Properties p = new Properties();
// Add a wrapper around reader object
p.load(reader);
// access properties data
System.out.println(p.getProperty("username"));
System.out.println(p.getProperty("password"));
}
}