0% found this document useful (0 votes)
2 views44 pages

Java Unit - 1

Java Database Connectivity (JDBC) is an API that allows Java applications to interact with relational databases, providing a standardized method for performing CRUD operations. JDBC architecture includes components like Java Application, JDBC API, DriverManager, JDBC Driver, and the Database, which work together to facilitate database communication. There are four types of JDBC drivers (Type 1, Type 2, Type 3, and Type 4), each with unique characteristics and use cases, with Type 4 being the most commonly used due to its efficiency and platform independence.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

Java Unit - 1

Java Database Connectivity (JDBC) is an API that allows Java applications to interact with relational databases, providing a standardized method for performing CRUD operations. JDBC architecture includes components like Java Application, JDBC API, DriverManager, JDBC Driver, and the Database, which work together to facilitate database communication. There are four types of JDBC drivers (Type 1, Type 2, Type 3, and Type 4), each with unique characteristics and use cases, with Type 4 being the most commonly used due to its efficiency and platform independence.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Unit - 1

Java Database Connectivity

Definition
Java Database Connectivity (JDBC) is an Application Programming Interface (API) in Java
that allows applications to communicate with relational databases. JDBC acts as a bridge
between Java applications and database management systems (DBMS), enabling developers
to perform operations such as inserting, retrieving, updating, and deleting (CRUD
operations) data from databases using SQL queries.

JDBC provides a standardized way to interact with databases, ensuring that Java applications
remain portable across different database systems without significant modifications.

Purpose and Architecture of JDBC

Purpose of JDBC

JDBC (Java Database Connectivity) is a standard Java API that enables Java applications to
interact with relational databases. It provides a uniform interface for accessing different
databases, allowing developers to write database-independent applications.

The primary purpose of JDBC is to establish a connection between Java programs and
databases, execute SQL statements, and retrieve and manipulate data stored in databases.
JDBC eliminates the need for database-specific coding by providing a common set of interfaces
and classes.

JDBC ensures portability, scalability, and maintainability of Java applications by allowing the
same Java code to work with multiple databases by simply changing the JDBC driver.

Objectives of JDBC
●​ To provide a standard API for database access in Java
●​ To enable database-independent application development
●​ To execute SQL queries and updates from Java programs
●​ To manage database connections efficiently
●​ To retrieve and process query results in Java applications

JDBC Architecture

JDBC architecture follows a layered approach that separates Java applications from
database-specific implementations. It consists of multiple components that work together to
enable database communication.

Components of JDBC Architecture

1. Java Application

The Java application represents the client program that requires access to the database. It uses
JDBC API classes and interfaces to interact with the database.

2. JDBC API
The JDBC API provides a set of standard interfaces and classes defined in the [Link] and
[Link] packages. These interfaces allow Java applications to perform database
operations such as establishing connections, executing SQL statements, and processing
results.

Key interfaces include:

●​ Driver
●​ Connection
●​ Statement
●​ PreparedStatement
●​ CallableStatement
●​ ResultSet

3. DriverManager

DriverManager is responsible for managing JDBC drivers. It selects the appropriate driver based
on the database URL and establishes a connection between the Java application and the
database.

4. JDBC Driver

A JDBC driver is a vendor-specific implementation that converts JDBC method calls into
database-specific requests. It acts as a communication link between the Java application and
the database.

5. Database

The database is the backend system where data is stored. It executes SQL queries received
from the JDBC driver and returns results to the Java application.

Working of JDBC Architecture

1.​ The Java application sends a request using JDBC API


2.​ DriverManager identifies and loads the appropriate JDBC driver
3.​ The JDBC driver establishes a connection with the database
4.​ SQL statements are sent to the database for execution
5.​ The database processes the request and returns the result
6.​ The result is delivered back to the Java application
Advantages of JDBC Architecture

●​ Database independence
●​ Platform independence
●​ Ease of maintenance
●​ Secure and efficient database access
●​ Supports enterprise-level applications

JDBC Drivers
JDBC Drivers are software components that allow Java applications to connect to databases.
They act as a bridge between a Java application and a database management system
(DBMS) by converting Java calls into database-specific operations.

Each database (MySQL, PostgreSQL, Oracle, SQL Server, etc.) requires a compatible JDBC
driver to communicate with it. JDBC drivers differ in how they handle this communication, which
leads to different performance levels and use cases.

There are four types of JDBC drivers, each with its own advantages and limitations.

1. JDBC-ODBC Bridge Driver (Type 1)


The JDBC-ODBC Bridge Driver uses the Open Database Connectivity (ODBC) driver to
interact with databases. ODBC is a standard API that allows applications to access database
management systems (DBMSs) regardless of the database vendor.

How It Works

●​ The Java application sends a database request to the JDBC-ODBC Bridge Driver.
●​ The bridge translates the request into an ODBC call.
●​ The ODBC driver communicates with the database and retrieves the requested data.
●​ The data is then sent back to the Java application.

Characteristics

✅ Works with any database that has an ODBC driver.​


✅ Can be used when there is no direct JDBC driver available for a database.
❌ Requires ODBC Setup, which can be complex.​
❌ Slower performance due to multiple translation layers.​
❌ Not platform-independent since it relies on native ODBC drivers.​
❌ Deprecated in Java 8 and removed in Java 9 due to security risks and inefficiency.
Example Usage (Before Deprecation)

import [Link];​​ ​ ​ ​ // Ummed Singh

import [Link];

import [Link];

public class Type1JDBCExample {

public static void main(String[] args) {

try {

[Link]("[Link]"); //
Load JDBC-ODBC Driver

Connection con =
[Link]("jdbc:odbc:myDSN", "user",
"password");

[Link]("Connected using Type 1


Driver");

[Link]();

} catch (Exception e) {

[Link]();

⚠ This code will not work in Java 8+ because the JDBC-ODBC Bridge has been removed.
2. Native API Driver (Type 2)
The Native API Driver interacts with the database using database vendor-specific native
libraries. It does not require an ODBC driver but depends on the database’s native client
software to function.

How It Works

●​ The Java application calls the Type 2 driver.


●​ The driver translates JDBC calls into native API calls provided by the database vendor.
●​ The database processes the request and returns the result via the native API.

Characteristics

✅ Better performance than Type 1 since it avoids ODBC overhead.​


✅ Works well when the native library is optimized for a particular database.
❌ Requires native database libraries, making it platform-dependent.​
❌ Must be installed on every client machine, increasing complexity.​
❌ Not suitable for web applications where clients may use different platforms.
Example Usage (Oracle Type 2 Driver)

import [Link];​ ​ ​ ​ ​ // Ummed Singh

import [Link];

import [Link];

public class Type2JDBCExample {

public static void main(String[] args) {

try {

[Link]("[Link]"); //
Oracle Native Driver

Connection con =
[Link]("jdbc:oracle:oci8:@localhost:1521:xe
", "user", "password");
[Link]("Connected using Type 2 Driver");

[Link]();

} catch (Exception e) {

[Link]();

📌 Requires Oracle’s native OCI (Oracle Call Interface) libraries installed on the system.

3. Network Protocol Driver (Type 3)


The Network Protocol Driver (also called Middleware Driver) communicates with the
database through a middleware server, which forwards the requests to the appropriate
database.

How It Works

●​ The Java application sends JDBC calls to the Type 3 driver.


●​ The driver forwards these calls to a middleware server over the network.
●​ The middleware translates them into database-specific calls and communicates with
the actual database.
●​ The database processes the request and sends the result back through the middleware.​

Characteristics

✅ More scalable than Type 1 and Type 2.​


✅ Database-independent – The middleware handles different database protocols.​
✅ Suitable for enterprise applications with centralized database management.
❌ Requires an additional middleware server, adding overhead.​
❌ Performance depends on network latency and middleware efficiency.
Example Usage

Middleware solutions like IBM WebSphere and Sybase use Type 3 drivers.

import [Link];​​ ​ ​ ​ // Ummed Singh

import [Link];

import [Link];

public class Type3JDBCExample {

public static void main(String[] args) {

try {

Connection con =
[Link]("jdbc:net://middleware-server:1
521/mydb", "user", "password");

[Link]("Connected using Type 3


Driver");

[Link]();

} catch (Exception e) {

[Link]();

📌 Rarely used today because Type 4 drivers provide better performance without middleware.

4. Thin Driver (Type 4)


The Thin Driver, also called the Pure Java Driver, is the most commonly used JDBC driver
today. It directly communicates with the database using its native protocol over the network.

How It Works

●​ The Java application sends JDBC calls to the Type 4 driver.


●​ The driver directly interacts with the database over TCP/IP using the database’s native
communication protocol.
●​ The database processes the request and returns the result directly to the application.

Characteristics

✅ Fastest and most efficient since it eliminates extra translation layers.​


✅ Pure Java implementation, making it platform-independent.​
✅ No additional software required, making deployment easier.​
✅ The preferred choice for most modern Java applications.
❌ Requires different drivers for different databases (e.g., MySQL, PostgreSQL, Oracle,
etc.).

Example Usage (MySQL Type 4 Driver)

import [Link];​​ ​ ​ ​ // Ummed Singh

import [Link];

public class Type4JDBCExample {

public static void main(String[] args) {

try {

[Link]("[Link]"); // MySQL
Thin Driver

Connection con =
[Link]("jdbc:mysql://localhost:3306/my
db", "root", "password");

[Link]("Connected using Type 4


Driver");

[Link]();
} catch (Exception e) {

[Link]();

📌 Most modern databases provide Type 4 JDBC drivers, such as PostgreSQL, MySQL,
Oracle, and SQL Server.

Steps to Connect to a Database using JDBC


To interact with a database using JDBC, a Java application follows a sequence of well-defined
steps. These steps ensure secure and efficient communication between the Java program and
the database.

Step 1: Load and Register the JDBC Driver

The JDBC driver acts as a communication link between the Java application and the database.
Loading the driver registers it with the DriverManager.

This step ensures that the appropriate database driver is available to establish a connection.

Step 2: Establish a Connection

A connection represents a session between the Java application and the database.​
The DriverManager class is used to create this connection using database URL, username,
and password.

Once the connection is established, the Java application can send SQL commands to the
database.
Step 3: Create a Statement Object

A Statement object is used to send SQL queries to the database.​


It allows execution of static SQL statements such as SELECT, INSERT, UPDATE, and DELETE.

The statement object works on the established database connection.

Step 4: Execute SQL Query

SQL queries are executed using the statement object.​


Depending on the type of SQL command, the execution may return a result or the number of
affected rows.

Step 5: Process the Result

When a SELECT query is executed, the database returns data in the form of a ResultSet.​
The ResultSet object stores the result of the query and allows the application to read data row
by row.

Step 6: Close the Connection

After completing database operations, all resources such as ResultSet, Statement, and
Connection must be closed to avoid memory leaks.

DriverManager
DriverManager is a class that manages a list of database drivers.​
It selects the appropriate driver based on the database URL and establishes a connection
between the Java application and the database.

Functions of DriverManager:

●​ Registers JDBC drivers


●​ Establishes database connections
●​ Manages multiple drivers
Connection
A Connection object represents a physical connection to the database.​
It acts as a gateway through which SQL statements are sent to the database.

Key responsibilities of Connection:

●​ Creates Statement and PreparedStatement objects


●​ Manages transactions
●​ Maintains session with the database

Statement
The Statement interface is used to execute simple SQL statements without parameters.

Characteristics:

●​ Used for static SQL queries


●​ SQL query is compiled every time it is executed
●​ Suitable for simple and one-time queries

PreparedStatement
PreparedStatement is a subinterface of Statement used for executing parameterized SQL
queries.

Characteristics:

●​ SQL query is precompiled


●​ Supports dynamic parameters
●​ Improves performance
●​ Protects against SQL Injection

PreparedStatement is preferred when the same query is executed multiple times with different
values.
ResultSet
ResultSet is an object that holds the data returned by a SELECT query.​
It acts like a table of data that can be traversed row by row.

Features of ResultSet:

●​ Maintains cursor position


●​ Retrieves data using column name or index
●​ Allows sequential access to query results

CRUD Operations Using JDBC


CRUD stands for Create, Read, Update, and Delete. These operations are performed using
JDBC with the following steps:

1. Establishing a Database Connection


import [Link];​ ​ ​ ​ ​ // Ummed Singh
import [Link];

public class DatabaseConnection {


public static Connection getConnection() {
Connection con = null;
try {
[Link]("[Link]");
con =
[Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");
[Link]("Connection Established
Successfully");
} catch (Exception e) {
[Link]();
}
return con;
}
}
2. Creating a Table in Database
import [Link];​ ​ ​ ​ ​ // Ummed Singh
import [Link];
public class CreateTable {​ ​ ​ ​ ​ // Ummed Singh
public static void main(String[] args) {
try {
Connection con = [Link]();
Statement stmt = [Link]();
String sql = "CREATE TABLE students (id INT PRIMARY
KEY, name VARCHAR(50), age INT)";
[Link](sql);
[Link]("Table Created Successfully");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

3. Insert Data into Database (Create Operation)


import [Link];​ ​ ​ ​ ​ // Ummed Singh
import [Link];
public class InsertData {
public static void main(String[] args) {
try {
Connection con = [Link]();
String query = "INSERT INTO students (id, name, age)
VALUES (?, ?, ?)";
PreparedStatement pstmt =
[Link](query);
[Link](1, 1);
[Link](2, "Ummed Singh");
[Link](3, 24);
[Link]();
[Link]("Data Inserted Successfully");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

4. Fetch Data from Database (Read Operation)


import [Link];​ ​ ​ ​ ​ // Ummed Singh
import [Link];​
import [Link];
public class ReadData {
public static void main(String[] args) {
try {
Connection con = [Link]();
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM
students");

[Link](“id”);
while ([Link]()) {
[Link]("ID: " + [Link]("id") + ",
Name: " + [Link]("name") + ", Age: " + [Link]("age"));
}
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

5. Update Data in Database (Update Operation)


import [Link];​ ​ ​ ​ ​ // Ummed Singh
import [Link];
public class UpdateData {
public static void main(String[] args) {
try {
Connection con = [Link]();
String query = "UPDATE students SET age = ? WHERE id
= ?";
PreparedStatement pstmt =
[Link](query);
[Link](1, 22);
[Link](2, 1);
[Link]();
[Link]("Data Updated Successfully");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

6. Delete Data from Database (Delete Operation)


import [Link];​ ​ ​ ​ ​ // Ummed Singh
import [Link];

public class DeleteData {


public static void main(String[] args) {
try {
Connection con = [Link]();
String query = "DELETE FROM students WHERE id = ?";
PreparedStatement pstmt =
[Link](query);
[Link](1, 1);
[Link]();
[Link]("Data Deleted Successfully");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

Non-Conventional Database
Non-conventional databases, also known as NoSQL databases, are different from traditional
relational databases (like MySQL, Oracle, PostgreSQL). Instead of storing data in tables with
rows and columns,they use different data storage techniques such as document-based,
key-value, column-family, or graph-based models.

🔹 Examples of Non-Conventional Databases:​


✅ MongoDB → Document-based (NoSQL).​
✅ Cassandra → Column-family-based (NoSQL).​
✅ Firebase → Cloud-based real-time database.​
✅ Redis → Key-value store (often used for caching).
These databases are schema-less, scalable, and flexible, and are great for handling
unstructured or semi-structured data.

JDBC (Java Database Connectivity) cannot be used directly with these databases. Instead,
Java provides custom drivers and APIs for connecting to them.

What Problems Do NoSQL Databases Solve?

Problem Solution by NoSQL

Rigid schema NoSQL is schema-less – different documents can have different


structures.

Performance Designed for high-speed read/write operations.


bottlenecks

Scalability Scales easily across multiple servers (horizontal scaling).

Handling Big Data Excellent for storing and querying massive datasets.

Complex relationships Graph databases handle relationships efficiently.

Introduction to MongoDB
MongoDB is a NoSQL database that stores data in JSON-like documents (BSON format). It is
used for applications that require scalability and flexibility. A typical MongoDB document
looks like this:
{
"_id": "12345",
"name": "Ummed Singh",
"email": "Ummed@[Link]",
"age": 24
}

MongoDB collections are like tables, and documents are like rows, but there is no strict schema.

🔹 Structure
●​ Database → contains collections
●​ Collection → contains documents
●​ Document → stores the actual data (like a row in SQL)
Collections Framework
Java Collections Framework

The Java Collections Framework is a unified architecture that provides a set of interfaces and
classes for storing and manipulating groups of data using various data structures and
algorithms.

For example, the LinkedList class in this framework implements a doubly-linked list data
structure, allowing efficient insertion and removal of elements.

Core Components

The framework includes a variety of interfaces, such as List, Set, Queue, and Map. These
interfaces define common operations that can be performed on collections, like adding,
removing, or accessing elements.

Why the Collections Framework?


The Java collections framework provides various data structures and algorithms that can be
used directly. This has two main advantages:

●​ We do not have to write code to implement these data structures and algorithms
manually.
●​ Our code will be much more efficient as the collections framework is highly optimized.

Moreover, the collections framework allows us to use a specific data structure for a particular
type of data. Here are a few examples,

●​ If we want our data to be unique, then we can use the Set interface provided by the
collections framework.
●​ To store data in key/value pairs, we can use the Map interface.
●​ The ArrayList class provides the functionality of resizable arrays.

Java Collection Interface

The Collection interface is the root interface in the Java Collections Framework hierarchy. It
defines the basic operations that can be performed on a group of elements.

Java does not directly provide implementations of the Collection interface itself. Instead, it
offers implementations for its subinterfaces, such as List, Set, and Queue, which define
more specific behaviors for different types of collections.
Collections Framework vs. Collection Interface

The Collections Framework is a comprehensive set of interfaces and classes in Java used to
store, manage, and manipulate groups of objects efficiently.

Within this framework, the Collection interface serves as the root interface for most
collection types, such as List, Set, and Queue.

However, the framework also includes other important interfaces that are not part of the
Collection hierarchy, such as:

●​ Map – for key-value pair data structures.


●​ Iterator – for traversing elements in a collection.

Subinterfaces of the Collection Interface

The Collection interface has several subinterfaces, each designed for specific types of data
handling. These subinterfaces inherit all the methods defined in the Collection interface and
may also introduce additional features tailored to their specific use.

Key Subinterfaces of the Collection Interface:

1. List Interface

The List interface represents an ordered collection of elements, similar to an array. It allows
elements to be added, accessed, or removed by index, and it supports duplicate elements.

Classes that Implement the List Interface

Since List is an interface, you cannot create objects directly from it. Instead, Java provides
several concrete classes that implement the List interface and offer its functionalities.

Here are the main classes that implement the List interface:

●​ ArrayList
●​ LinkedList
●​ Stack
●​ Vector

These classes are part of the Java Collections Framework and each has its own way of
storing and managing elements, while still following the behavior defined by the List interface.
How to Use the List Interface in Java

To use the List interface in Java, you need to import it from the [Link] package.

Example:

public static void main(String[] args) {​ ​ // Ummed Singh

int[] arr1 = new int[10];

List<Integer> arr = new ArrayList<>();

[Link](10);

[Link](20);

[Link](50);

[Link](20);

[Link](30);

// Size + size/2 = 10 + 5 = 15;

[Link]([Link](1));

[Link]([Link]());

[Link]([Link](0));

[Link]([Link](0));

[Link]([Link]());

Methods of the List Interface

The List interface inherits all the methods from the Collection interface, as Collection is a
superinterface of List.
In addition to the methods provided by the Collection interface, the List interface also includes
methods that are specific to handling ordered collections and managing elements by index.

Some of the commonly used methods from the Collection interface, which are also available in
the List interface, include:

Methods Description

add() adds an element to a list

addAll() adds all elements of one list to another

get() helps to randomly access elements from lists

iterator() returns iterator object that can be used to sequentially access elements of
lists

set() changes elements of lists

remove() removes an element from the list

removeAll() removes all the elements from the list

clear() removes all the elements from the list (more efficient than removeAll())

size() returns the length of lists

toArray() converts a list into an array

contains() returns true if a list contains specific element

Implementation of the List Interface

1. Implementing the ArrayList Class


In Java, the ArrayList class is used to implement the functionality of resizable arrays. It
provides a flexible and dynamic way to store elements, as it implements the List interface of
the Collections Framework.

Java ArrayList vs. Array

In Java, when using an array, you must specify its size at the time of declaration. Once the size
is set, it cannot be changed.

int[] numbers = new int[5]; // Fixed size array

However, this can be limiting if the number of elements is unknown or changes frequently. To
solve this problem, Java provides the ArrayList class, which allows for resizable arrays.

Unlike arrays, ArrayList can automatically adjust its capacity when elements are added or
removed. This makes ArrayList a dynamic array, offering more flexibility and ease of use in
scenarios where the size of the collection may change over time.

Example
class CustomArrayList<E>{​ ​ ​ ​ ​ // Ummed Singh
private static final int DEFAULT_CAPACITY = 2;
private Object[] elements;
private int size = 0;
public CustomArrayList(){
elements = new Object[DEFAULT_CAPACITY];
}
public void add(E ele){
ensureCapacity();
elements[size] = ele;
size++;
}
public E get(int index){
checkIndex(index);
return (E) elements[index];
}
// {10, 20, 30, 40}; -> {10, 30, 40, 40} -> {10, 20, 30,
null} size--;
public void remove(int index){
checkIndex(index);
for (int i = index; i<size -1; i++){
elements[i] = elements[i+1];
}
elements[size-1] = null;
size--;
}

void checkIndex(int index){


if(index < 0 || index >= size){
throw new IndexOutOfBoundsException("Index: " + index
+ " Size: " +size);
}
}

void ensureCapacity(){
if(size == [Link]){
int newCapacity = [Link] + ([Link]
/2);
elements = [Link](elements, newCapacity);
}
}
int size(){
return size;
}

}
public class ArrayListImplementationDemo {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();


CustomArrayList<Integer> cusList = new
CustomArrayList<>();
[Link](10);
[Link](20);
[Link](30);

[Link]([Link]());
[Link]([Link](4));
[Link](1);
[Link]([Link]());
}
}

Methods of ArrayList Class


Here are some more ArrayList methods that are commonly used.

Methods Descriptions

size() Returns the length of the arraylist.

sort() Sort the arraylist elements.

clone() Creates a new arraylist with the same element, size, and capacity.

contains() Searches the arraylist for the specified element and returns a boolean
result.

ensureCapacity() Specifies the total element the arraylist can contain.

isEmpty() Checks if the arraylist is empty.

indexOf() Searches a specified element in an arraylist and returns the index of


the element.

Implementing the LinkedList Class

●​ LinkedList implements both Deque and List interface.


●​ Means it support Dequeue methods like: "getFirst", "getLast", "removeFirst",
"removeLast" etc...
●​ It also support index based operations like List: "get(index)", "add(index, object)" etc.

Example:
public static void main(String[] args) {​ ​ // Ummed Singh
// 1. pre
// 2. next
// 3. data

LinkedList<Integer> list = new LinkedList<>();


[Link](10);
[Link]([Link](1));

Time Complexity:
●​ Insertion at start and end: O(1)
●​ Insertion at particular index: O(n) for lookup of the index + O(1) for adding
●​ Search: O(n)
●​ Deletion at start or end: O(1)
●​ Deletion at specific index: O(n) for the lookup of the index + O(1) for removal
Space Complexity: O(n)

Stack
●​ Represent LIFO (Last in First out) operation
●​ Since it extends Vector, its method is also Synchronized.
●​ How its different from Deque: Deque is not thread safe, stack is.

public class StackExample { //Ummed Singh


public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
[Link](10);
[Link](20);

[Link]([Link]());
}
}
Time Complexity:
●​ Insertion: O(1)
●​ Deletion: O(1)
●​ Search: O(n)
Space Complexity: O(n)

Queue Interface
The Queue interface is used when we want to store and access elements in a First In, First Out
manner.
The Queue interface of the Java collections framework provides the functionality of the queue
data structure. It extends the Collection interface.

Classes that Implement Queue

Since the Queue is an interface, we cannot provide the direct implementation of it.
In order to use the functionalities of Queue, we need to use classes that implement it:
●​ ArrayDeque
●​ LinkedList
●​ PriorityQueue

Interfaces that extend Queue

The Queue interface is also extended by various subinterfaces:

●​ Deque
●​ BlockingQueue
●​ BlockingDeque
Working of Queue Data Structure

In queues, elements are stored and accessed in First In, First Out manner. That is, elements are
added from the behind and removed from the front.

How to use Queue?


In Java, we must import [Link] package in order to use Queue.

// LinkedList implementation of Queue​ ​ ​

Queue<String> animal1 = new LinkedList<>();

// Array implementation of Queue

Queue<String> animal2 = new ArrayDeque<>();

// Priority Queue implementation of Queue

Queue<String> animal3 = new PriorityQueue<>();


Methods of Queue
The Queue interface includes all the methods of the Collection interface. It is because Collection
is the super interface of Queue.
Some of the commonly used methods of the Queue interface are:

●​ add() - Inserts the specified element into the queue. If the task is successful, add()
returns true, if not it throws an exception.
●​ offer() - Inserts the specified element into the queue. If the task is successful, offer()
returns true, if not it returns false.
●​ element() - Returns the head of the queue. Throws an exception if the queue is empty.
●​ peek() - Returns the head of the queue. Returns null if the queue is empty.
●​ remove() - Returns and removes the head of the queue. Throws an exception if the
queue is empty.
●​ poll() - Returns and removes the head of the queue. Returns null if the queue is empty.

Implementation of the Queue Interface


Queue<Integer> arr = new ArrayDeque<>();
Queue<Integer> queue = new LinkedList<>();
Queue<Integer> list = new PriorityQueue<>();

PriorityQueue
●​ Its of 2 types, Minimum Priority Queue and Maximum Priority Queue
●​ It is based on priority Heap (Min Heap and Max Heap).
●​ Elements are ordered according to either Natural Ordering (by default) or by Comparator
provided during queue construction time.

1.​ MinPriorityQueue: min priority queue, used to solve problems of min heap.

public class MinPriorityQueueExample {

public static void main(String args[]){


//min priority queue, used to solve problems of min heap.
PriorityQueue<Integer> minPQ= new PriorityQueue<>();
[Link](5);
[Link](2);
[Link](8);
[Link](1);
//lets print all the values
[Link]((Integer val) -> [Link](val));
//remove top element from the PQ and print
while(![Link]())
{
int val = [Link]();
[Link]("remove from top:" + val);
}
}
}

Output:
1
2
8
5
remove from top:1
remove from top:2
remove from top:5
remove from top:8

2.​ MaxPriorityQueue: max priority queue, used to solve problems of max heap

public class MaxPriorityQueue {


public static void main(String args[]){
//max priority queue, used to solve problems of max heap
PriorityQueue<Integer> maxPQ = new PriorityQueue<>((Integer a,
Integer b) -> b-a);
[Link](5);
[Link](2);
[Link](8);
[Link](1);
//lets print all the values
[Link]((Integer val) -> [Link](val));
//remove top element from the PQ and print
while(![Link]()){
int val = [Link]();
[Link]("remove from top:" + val);
}
}
}

Output:
​ 8
2
5
1
remove from top:8
remove from top:5
remove from top:2
remove from top:1

Map Interface
In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique
names that can be used to access a particular element in a map. And, each key has a single
value associated with it.

We can access and modify values using the keys associated with them.
In the above diagram, we have values: United States, Brazil, and Spain. And we have
corresponding keys: us, br, and es.
Now, we can access those values using their corresponding keys.
Note: The Map interface maintains 3 different sets:
●​ the set of keys
●​ the set of values
●​ the set of key/value associations (mapping).

Hence we can access keys, values, and associations individually.

Classes that implement Map


Since Map is an interface, we cannot create objects from it.
In order to use the functionalities of the Map interface, we can use these classes:
●​ HashMap
●​ EnumMap
●​ LinkedHashMap
●​ WeakHashMap
●​ TreeMap
These classes are defined in the collections framework and implemented in the Map interface.

Java Map Subclasses

Interfaces that extend Map


The Map interface is also extended by these subinterfaces:
●​ SortedMap
●​ NavigableMap
●​ ConcurrentMap

How to use Map?


In Java, we must import the [Link] package in order to use Map. Once we import the
package, here's how we can create a map.

// Map implementation using HashMap


Map<Key, Value> numbers = new HashMap<>();
In the above code, we have created a Map named numbers. We have used the HashMap class
to implement the Map interface.
Here,
●​ Key - a unique identifier used to associate each element (value) in a map
●​ Value - elements associated by keys in a map

Methods of Map
The Map interface includes the following methods:
●​ put(K, V) - Inserts the association of a key K and a value V into the map. If the key is
already present, the new value replaces the old value.
●​ putAll() - Inserts all the entries from the specified map to this map.
●​ putIfAbsent(K, V) - Inserts the association if the key K is not already associated with the
value V.
●​ get(K) - Returns the value associated with the specified key K. If the key is not found, it
returns null.
●​ getOrDefault(K, defaultValue) - Returns the value associated with the specified key K.
If the key is not found, it returns the defaultValue.
●​ containsKey(K) - Checks if the specified key K is present in the map or not.
●​ containsValue(V) - Checks if the specified value V is present in the map or not.
●​ replace(K, V) - Replace the value of the key K with the new specified value V.
●​ replace(K, oldValue, newValue) - Replaces the value of the key K with the new value
newValue only if the key K is associated with the value oldValue.
●​ remove(K) - Removes the entry from the map represented by the key K.
●​ remove(K, V) - Removes the entry from the map that has key K associated with value V.
●​ keySet() - Returns a set of all the keys present in a map.
●​ values() - Returns a set of all the values present in a map.
●​ entrySet() - Returns a set of all the key/value mapping present in a map.

Implementing HashMap Class


The HashMap class of the Java collections framework provides the functionality of the hash
table data structure.
It stores elements in key/value pairs. Here, keys are unique identifiers used to associate each
value on a map.
The HashMap class implements the Map interface.
Create a HashMap
In order to create a hash map, we must import the [Link] package first. Once we
import the package, here is how we can create hashmaps in Java.

// hashMap creation with 8 capacity and 0.6 load factor


HashMap<K, V> numbers = new HashMap<>();

In the above code, we have created a hashmap named numbers. Here, K represents the key
type and V represents the type of values. For example,

HashMap<String, Integer> numbers = new HashMap<>();

Here, the type of keys is String and the type of values is Integer.

Example 1: Create HashMap in Java


import [Link];​ ​ ​ ​ ​ // Ummed Singh
public class HashMapDemo {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();
// add elements to hashmap
[Link]("Java", 8);
[Link]("JavaScript", 1);
[Link]("Python", 3);
[Link]("HashMap: " + languages);
}
}

In the above example, we have created a HashMap named languages.


Here, we have used the put() method to add elements to the hashmap.

Basic Operations on Java HashMap


The HashMap class provides various methods to perform different operations on hashmaps. We
will look at some commonly used arraylist operations in this tutorial:
●​ Add elements
●​ Access elements
●​ Change elements
●​ Remove elements
public static void main(String[] args) {​ ​ // Ummed Singh

// Creating a map using the HashMap

Map<String, Integer> numbers = new HashMap<>();

// Insert elements to the map

[Link]("One", 1);

[Link]("Two", 2);

[Link]("Map: " + numbers);

// Access keys of the map

[Link]("Keys: " + [Link]());

// Access values of the map

[Link]("Values: " + [Link]());

// Access entries of the map

[Link]("Entries: " + [Link]());

// Remove Elements from the map


int value = [Link]("Two");

[Link]("Removed Value: " + value);

Other Methods of HashMap

Method Description

clear() removes all mappings from the HashMap

compute() computes a new value for the specified key

computeIfAbsent() computes value if a mapping for the key is not present

computeIfPresent() computes a value for mapping if the key is present

merge() merges the specified mapping to the HashMap

clone() makes the copy of the HashMap

containsKey() checks if the specified key is present in Hashmap

containsValue() checks if Hashmap contains the specified value

size() returns the number of items in HashMap

isEmpty() checks if the Hashmap is empty


Iterate through a HashMap
To iterate through each entry of the hashmap, we can use Java for-each loop. We can
iterate through keys only, values only, and key/value mapping. For example,

public class IterateHashMapDemo {​ ​ ​ ​ // Ummed Singh

public static void main(String[] args) {

// create a HashMap

HashMap<Integer, String> languages = new HashMap<>();

[Link](1, "Java");

[Link](2, "Python");

[Link](3, "JavaScript");

[Link]("HashMap: " + languages);

// iterate through keys only

[Link]("Keys: ");

for (Integer key : [Link]()) {

[Link](key);

[Link](", ");

// iterate through values only

[Link]("\nValues: ");

for (String value : [Link]()) {

[Link](value);
[Link](", ");

// iterate through key/value entries

[Link]("\nEntries: ");

for (Entry<Integer, String> entry : [Link]())


{

[Link](entry);

[Link](", ");

Note that we have used the [Link] in the above example. It is the nested class of
the Map interface that returns a view (elements) of the map.

We first need to import the [Link] package in order to use this class.

This nested class returns a view (elements) of the map.

Creating HashMap from Other Maps

In Java, we can also create a hashmap from other maps. For example,

import [Link];​ ​ ​ ​ ​ // Ummed Singh

import [Link];

public class OtherHashMapDemo {

public static void main(String[] args) {


// create a treemap

TreeMap<String, Integer> evenNumbers = new TreeMap<>();

[Link]("Two", 2);

[Link]("Four", 4);

[Link]("TreeMap: " + evenNumbers);

// create hashmap from the treemap

HashMap<String, Integer> numbers = new


HashMap<>(evenNumbers);

[Link]("Three", 3);

[Link]("HashMap: " + numbers);

In the above example, we have created a TreeMap named evenNumbers. Notice the
expression,

numbers = new HashMap<>(evenNumbers)

Note: While creating a hashmap, we can include optional parameters: capacity and
load factor. For example,

HashMap<K, V> numbers = new HashMap<>(8, 0.6f);

●​ 8(capacity is 8) - This means it can store 8 entries.


●​ 0.6f (load factor is 0.6) - This means whenever our hash table is filled by 60%, the
entries are moved to a new hash table double the size of the original hash table.
If the optional parameters are not used, then the default capacity will be 16 and the default load
factor will be 0.75.

Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics.
It cannot have duplicate elements.

Java List vs. Set


Both the List interface and the Set interface inherit the Collection interface. However, there
exists some difference between them.
●​ Lists can include duplicate elements. However, sets cannot have duplicate elements.
●​ Elements in lists are stored in some order. However, elements in sets are stored in
groups like sets in mathematics.

Classes that implement Set


Since Set is an interface, we cannot create objects from it.
In order to use functionalities of the Set interface, we can use these classes:
●​ HashSet
●​ LinkedHashSet
●​ EnumSet
●​ TreeSet
These classes are defined in the Collections framework and implement the Set interface.

Interfaces that extend Set


The Set interface is also extended by these subinterfaces:
●​ SortedSet
●​ NavigableSet

How to use Set?


In Java, we must import [Link] package in order to use Set.
// Set implementation using HashSet​ ​ ​ // Ummed Singh
Set<String> animals = new HashSet<>();

Here, we have created a Set called animals. We have used the HashSet class to implement the
Set interface.

Methods of Set
The Set interface includes all the methods of the Collection interface. It's because Collection is a
super interface of Set.
Some of the commonly used methods of the Collection interface that's also available in the Set
interface are:
●​ add() - adds the specified element to the set
●​ addAll() - adds all the elements of the specified collection to the set
●​ iterator() - returns an iterator that can be used to access elements of the set
sequentially
●​ remove() - removes the specified element from the set
●​ removeAll() - removes all the elements from the set that is present in another specified
set
●​ retainAll() - retains all the elements in the set that are also present in another specified
set
●​ clear() - removes all the elements from the set
●​ size() - returns the length (number of elements) of the set
●​ toArray() - returns an array containing all the elements of the set
●​ contains() - returns true if the set contains the specified element
●​ containsAll() - returns true if the set contains all the elements of the specified collection
●​ hashCode() - returns a hash code value (address of the element in the set)

Set Operations
The Java Set interface allows us to perform basic mathematical set operations like union,
intersection, and subset.
●​ Union - to get the union of two sets x and y, we can use [Link](y)
●​ Intersection - to get the intersection of two sets x and y, we can use [Link](y)
●​ Subset - to check if x is a subset of y, we can use [Link](x)

Implementation of the Set Interface


Implementing HashSet Class

import [Link];​ ​ ​ ​ ​ ​ // Ummed Singh

import [Link];

public class HashSetDemo {

public static void main(String[] args) {

// Creating a set using the HashSet class

Set<Integer> set1 = new HashSet<>();

// Add elements to the set1

[Link](2);

[Link](3);

[Link]("Set1: " + set1);

// Creating another set using the HashSet class

Set<Integer> set2 = new HashSet<>();


// Add elements

[Link](1);

[Link](2);

[Link]("Set2: " + set2);

// Union of two sets

[Link](set1);

[Link]("Union is: " + set2);

You might also like