Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

java_unit_4

The document outlines the Java Programming course objectives and learning outcomes for B.Tech students at Pimpri Chinchwad University, focusing on key concepts such as multithreading, JDBC, and GUI design. It covers the fundamentals of Java, including object-oriented principles, exception handling, and database connectivity. Additionally, it provides details on thread life cycles, types of JDBC drivers, and includes assignment questions to reinforce learning.

Uploaded by

rishiadik55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

java_unit_4

The document outlines the Java Programming course objectives and learning outcomes for B.Tech students at Pimpri Chinchwad University, focusing on key concepts such as multithreading, JDBC, and GUI design. It covers the fundamentals of Java, including object-oriented principles, exception handling, and database connectivity. Additionally, it provides details on thread life cycles, types of JDBC drivers, and includes assignment questions to reinforce learning.

Uploaded by

rishiadik55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

PCET’S Pimpri Chinchwad University

Department of Computer Science and Engineering


Course Name : Java Programming
Course Code/Course Type : UBTCE212/PCC
SY. B.Tech

Prepared By: Mr. Tushar R. Mahore

PIMPRI CHINCHWAD UNIVERSITY


Course Objectives (CO):
• The objectives of Java Programming are:
▫ To learn the fundamentals of the Java programming language.
▫ To learn object-oriented principles like abstraction, encapsulation,
inheritance, and polymorphism and apply them in solving problems using
java.
▫ To apply the concepts of exception handling, multithreading and collection
classes using java.
▫ To develop software applications using JDBC connectivity.
▫ To design the Graphical User Interface using applets and swing controls.
PIMPRI CHINCHWAD UNIVERSITY
Course Learning Outcomes (CLO):
• Students would be able to:
▫ To grasp the fundamentals programming concepts of Java programming
language.
▫ To apply object-oriented principles like abstraction, encapsulation,
inheritance, polymorphism in solving problems using java.
▫ To perform exception handling, multithreading code using java.
▫ To develop software applications using JDBC connectivity.
▫ To design the Graphical User Interface using event handling.

PIMPRI CHINCHWAD UNIVERSITY


UNIT- IV
Multithreading, Databases

PIMPRI CHINCHWAD UNIVERSITY


Multithreading in Java - Introduction
• Multithreading is a process of executing two or more threads
simultaneously to maximize CPU utilization.
• A thread is the smallest unit of a process that can be scheduled and executed
by the CPU.
• Multithreading improves the performance of an application by allowing
multiple tasks to run conzcurrently within the same program.

PIMPRI CHINCHWAD UNIVERSITY


Why Use Multithreading?
• Better CPU utilization by running multiple threads simultaneously.
• Faster execution of tasks (since threads can run concurrently).
• Helps in developing responsive and interactive applications.

PIMPRI CHINCHWAD UNIVERSITY


Difference Between Multiple Processes and Multiple
Threads
Feature Multiple Processes Multiple Threads

A process is an independent A thread is a lightweight sub-process


Definition:
program in execution within a process

Threads share memory within the same


Memory Sharing: Processes do not share memory
process
More expensive (needs more
Creation: Less expensive (lightweight)
resources)
Inter-process communication (IPC) Shared memory allows direct
Communication:
needed communication
Context Expensive due to full process state
Less expensive since memory is shared
Switching: switch
Threads within a process can run
Execution: Processes run independently
concurrently

PIMPRI CHINCHWAD UNIVERSITY


Thread Life Cycle
• A thread in Java can be in one of the following states:

1. NEW – Thread is created but not started yet.


2. RUNNABLE – Thread is ready to run and waiting for CPU
scheduling.
3. BLOCKED – Thread is waiting for a monitor lock to be released.
4. WAITING – Thread is waiting indefinitely for another thread to
notify it.
5. TIMED_WAITING – Thread is waiting for a specified time.
6. TERMINATED – Thread has finished execution.

PIMPRI CHINCHWAD UNIVERSITY


Thread Life Cycle

PIMPRI CHINCHWAD UNIVERSITY


Working with Threads – Creating Threads
• There are two ways to create a thread in Java:
• Extending the Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread and calls run()
}
}

PIMPRI CHINCHWAD UNIVERSITY


Working with Threads – Creating Threads
• There are two ways to create a thread in Java:
• Implementing the Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running...");
}
}

public class Main {


public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
t1.start();
}
}
PIMPRI CHINCHWAD UNIVERSITY
Working with Threads – Interrupting Threads
• You can interrupt a thread using the interrupt() method.
class MyThread extends Thread {
public void run() {
try {
Thread.sleep(5000);
System.out.println("Thread completed");
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}}}

public class Main {


public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
t.interrupt(); // Interrupting the thread
}
}
PIMPRI CHINCHWAD UNIVERSITY
Thread Priorities
• Each thread in Java has a priority between 1 (MIN_PRIORITY) to 10
(MAX_PRIORITY). The default priority is 5 (NORM_PRIORITY).
class MyThread extends Thread {
public void run() {
System.out.println("Running thread with priority: " +
this.getPriority());
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setPriority(Thread.MAX_PRIORITY); // Set
priority to 10
t1.start();
}
}
PIMPRI CHINCHWAD UNIVERSITY
public class Main {
Synchronizing Threads public static void main(String[] args) {
Counter counter = new Counter();

• Used to prevent race conditions. Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) counter.increment();
• Achieved using the synchronized });

keyword. Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) counter.increment();
});
class Counter { t1.start();
private int count = 0; t2.start();
public synchronized void increment() { try {
count++; t1.join();
} t2.join();
} catch (InterruptedException e) {}
public int getCount() { System.out.println("Count: " + counter.getCount());
return count; }
} }
} PIMPRI CHINCHWAD UNIVERSITY
Interthread Communication (Producer-Consumer
Problem)

• wait() – Makes thread wait until another thread invokes notify() or notifyAll().
• notify() – Wakes up one waiting thread.
• notifyAll() – Wakes up all waiting threads.

PIMPRI CHINCHWAD UNIVERSITY


class SharedResource { public class Main {
private boolean available = false; public static void main(String[] args) {
SharedResource resource = new SharedResource();
public synchronized void produce() throws
InterruptedException { Thread producer = new Thread(() -> {
while (available) { try {
wait(); resource.produce();
} } catch (InterruptedException e) {}
System.out.println("Produced"); });
available = true;
notify(); Thread consumer = new Thread(() -> {
} try {
public synchronized void consume() throws resource.consume();
InterruptedException { } catch (InterruptedException e) {}
while (!available) { });
wait();
} producer.start();
System.out.println("Consumed"); consumer.start();
available = false; }
notify(); }
}
} PIMPRI CHINCHWAD UNIVERSITY
Database Management (JDBC) - Introduction
• A Database is an organized collection of data that can be stored, managed, and
retrieved efficiently.
• Types of Databases
1. Relational Databases (RDBMS)
2. Non-Relational Databases (NoSQL)
3. In-Memory Databases

PIMPRI CHINCHWAD UNIVERSITY


Relational Database Management Systems (RDBMS)
1. RDBMS is the most commonly used type of database.
2.Data is stored in tables consisting of:
1. Columns – Represent the attributes or fields.
2. Rows – Represent the individual records.
3. Primary Key – Uniquely identifies each row.
4. Foreign Key – Refers to the primary key of another table.
• Example of RDBMS Structure
id name age course

1 Parikshit 20 CS

2 Mayur 21 IT
PIMPRI CHINCHWAD UNIVERSITY
Structured Query Language (SQL)
• Basic SQL Commands
▫ DDL (Data Definition Language) – Defines the structure of the database
 CREATE, ALTER, DROP
▫ DML (Data Manipulation Language) – Manipulates the data in the table
 INSERT, UPDATE, DELETE
▫ DQL (Data Query Language) – Query the data
 SELECT
▫ TCL (Transaction Control Language) – Manage transactions.
 COMMIT, ROLLBACK
▫ DCL (Data Control Language) – Manage access.
 GRANT, REVOKE
PIMPRI CHINCHWAD UNIVERSITY
Java Database Connectivity (JDBC)
• JDBC (Java Database Connectivity) is an API (Application Programming
Interface) that enables Java applications to interact with relational databases.

PIMPRI CHINCHWAD UNIVERSITY


Why Use JDBC?
• Java provides a direct connection to the database using JDBC.
• JDBC allows:
• Executing SQL queries.
• Storing and retrieving data.
• Managing database connections.
• Handling transactions.

PIMPRI CHINCHWAD UNIVERSITY


JDBC Architecture
• JDBC follows a multi-layered architecture:
1. Application Layer – Java code that makes requests.
2. JDBC API Layer – Java library that provides database connection.
3. Driver Layer – JDBC Driver that translates API calls into native database
calls.
4. Database Layer – The actual database.

PIMPRI CHINCHWAD UNIVERSITY


JDBC Components

Component Description

DriverManager Manages database drivers.

Represents a session with a


Connection
database.

Statement Executes SQL queries.

PreparedStatement Executes parameterized queries.

CallableStatement Executes stored procedures.

ResultSet Holds the data returned by queries.

PIMPRI CHINCHWAD UNIVERSITY


JDBC Driver Types
• JDBC uses drivers to connect to different databases. There are 4 types of
drivers:
• Type 1 – JDBC-ODBC Bridge Driver
• Uses ODBC (Open Database Connectivity) driver to connect to the
database.
• Platform-dependent and deprecated in Java 8.

• Example:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:testdb");

PIMPRI CHINCHWAD UNIVERSITY


JDBC Driver Types
• Type 2 – Native API Driver
• Uses the native API of the database.
• Requires native libraries to be installed.
• Platform-dependent.
• Example: Oracle native driver:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "user", "password");

PIMPRI CHINCHWAD UNIVERSITY


JDBC Driver Types
• Type 3 – Network Protocol Driver
• Uses a middleware server to translate JDBC calls into database-specific
calls.
• Works over the network.
• Slower due to the network overhead.
• Example:
Class.forName("com.example.networkdriver.Driver");
Connection con = DriverManager.getConnection("jdbc:network://localhost:3306/testdb");

PIMPRI CHINCHWAD UNIVERSITY


JDBC Driver Types
• Type 4 – Thin Driver
• Directly connects Java to the database using the database's
communication protocol.
• Platform-independent and fastest driver.
• Example: MySQL thin driver:

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");

PIMPRI CHINCHWAD UNIVERSITY


Steps to Connect to a Database Using JDBC
1. Load the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

2. Create a Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");

3. Create a Statement
Statement stmt = con.createStatement();

PIMPRI CHINCHWAD UNIVERSITY


Steps to Connect to a Database Using JDBC
4. Execute the Query
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

5. Process the Result


while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}

6. Close the Connection


con.close();

PIMPRI CHINCHWAD UNIVERSITY


JDBC Transactions
• A transaction is a sequence of one or more SQL statements that must be executed
as a single unit.
• ACID Properties
1. Atomicity – Entire transaction is successful or none.
2. Consistency – Data remains consistent after the transaction.
3. Isolation – Transactions do not interfere with each other.
4. Durability – Changes remain permanent even after a crash.

PIMPRI CHINCHWAD UNIVERSITY


JDBC Transactions
• Example of Transaction Handling
con.setAutoCommit(false); // Start transaction

Statement stmt = con.createStatement();


stmt.executeUpdate("UPDATE students SET age = 21 WHERE id = 1");

// Commit the transaction


con.commit();

PIMPRI CHINCHWAD UNIVERSITY


Using DAO (Data Access Object) Pattern
• DAO separates the database logic from the business logic
• DAO Example: StudentDAO.java
public class StudentDAO {
public List<Student> getAllStudents() {
List<Student> students = new ArrayList<>();
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

while (rs.next()) {
students.add(new Student(rs.getInt(1), rs.getString(2), rs.getInt(3)));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
PIMPRI CHINCHWAD UNIVERSITY
Using DAO (Data Access Object) Pattern
• DAO Example: StudentDAO.java
public class StudentDAO {
public List<Student> getAllStudents() {
List<Student> students = new ArrayList<>();
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
students.add(new Student(rs.getInt(1), rs.getString(2), rs.getInt(3)));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
} PIMPRI CHINCHWAD UNIVERSITY
Using DAO (Data Access Object) Pattern
• DAO Example: Main.java

public class Main {


public static void main(String[] args) {
StudentDAO dao = new StudentDAO();
dao.getAllStudents().forEach(System.out::println);
}
}

PIMPRI CHINCHWAD UNIVERSITY


Assignment Questions
1. What is the difference between a process and a thread?
2. Explain the lifecycle of a thread with a diagram.
3. Modify the above program to create multiple producers and consumers.
4. Write a program to create a thread using the Runnable interface.
5. Explain the purpose of wait(), notify(), and notifyAll() in multithreading.
6. Write a Java program to create two threads:
• One thread should print even numbers from 1 to 100.
• The other thread should print odd numbers from 1 to 100.
Ensure that both threads run concurrently and print results sequentially.
PIMPRI CHINCHWAD UNIVERSITY
Assignment Questions
7. Write a Java program to demonstrate the concept of thread priority by
creating three threads with different priorities (MIN_PRIORITY,
NORM_PRIORITY, MAX_PRIORITY). Print the execution order of the
threads.
8. What are the different types of JDBC drivers?
9. Explain the difference between Statement and PreparedStatement.
10. Modify the program to update and delete records from the database.
11. Write a program to create a new table in the database using JDBC.
12. Explain the purpose of ResultSet in JDBC.
PIMPRI CHINCHWAD UNIVERSITY
Assignment Questions
13. Write a Java program to connect to a MySQL database and create a table named
Employee with the following fields:
▫ id (int) – Primary key
▫ name (varchar)
▫ salary (float)
 Insert at least 5 records into the table using a PreparedStatement and display
all the records.
14. Write a Java program to update the salary of an employee in the Employee table
based on the employee ID. Display the updated table data.
15. Write a Java program to delete an employee's record based on the employee ID
from the Employee table. Ensure that the table data is updated correctly after
deletion.

PIMPRI CHINCHWAD UNIVERSITY


PIMPRI CHINCHWAD UNIVERSITY

You might also like