0% found this document useful (0 votes)
15 views56 pages

Unit 3 App

APP JAVA material

Uploaded by

signtanviraina
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)
15 views56 pages

Unit 3 App

APP JAVA material

Uploaded by

signtanviraina
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
You are on page 1/ 56

Unit-3 - Advanced Java

Programming Paradigms
Concurrent Programming Paradigm: Multithreading and Multitasking; Thread classes
and methods - Declarative Programming Paradigm: Java Database Connectivity
(JDBC); Connectivity with MySQL – Query Execution; - Graphical User Interface
Based Programming Paradigm: Java Applet: Basics and Java Swing: Model View
Controller (MVC) and Widgets; Develop a java project dissertation based on the
programming paradigm.
Concurrent Programming:

• This means that tasks appear to run simultaneously, but under the hood, the system
might really be switching back and forth between the tasks.
• it is beneficial even on a single processor machine.

Concurrent Programming on Single Processor Machine:


Suppose the user needs to download five images and each image is coming from a
different server, and each image takes five seconds, and now suppose the user download
all of the first images, it takes 5 seconds, then all of the second images, it takes another 5
seconds, and so forth, and by the end of the time, it took 25 seconds. It is faster to
download a little bit of image one, then a little bit of image two, three, four, five and then
come back and a little bit of image one and so forth.
Need of Concurrent Programming

Threads are useful only when the task is relatively large and pretty much
self contained. When the user needs to perform only a small amount of
combination after a large amount of separate processing, there’s some
overhead to starting and using threads. So if the task is really small, one
never get paid back for the overhead.

threads are most useful when the users are waiting. For instance, while
one is waiting for one server, the other can be reading from another
server.
Advantages:
Loose Coupling: Since a separate class can be reused, it promotes loose coupling.
Constructors: Arguments can be passed to constructors for different cases. For example,
describing different loop limits for threads.
Race Conditions: If the data has been shared, it is unlikely that a separate class would be
used as an approach and if it does not have a shared data, then no need to worry about the race
conditions.

Disadvantages:
It was a little bit inconvenient to call back to the main application. A reference had to be
passed along the constructor, and even if there is access to reference, only public
methods(pause method in the given example) in the main application can be called.
Multithreading

Multithreading is a Java feature that allows concurrent execution of two or


more parts of a program for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight
processes within a process.

Threads can be created by using two mechanisms :


• Extending the Thread class
• Implementing the Runnable Interface
class MyThread extends Thread { 10 Value: 0
public void run() { 11 Value: 0
for (int i = 0; i < 5; i++) { 11 Value: 1
System.out.println(Thread.currentThread().getId() + " Value: " + i); 10 Value: 1
} 10 Value: 2
} 10 Value: 3
} 10 Value: 4
11 Value: 2
public class Main { 11 Value: 3
public static void main(String[] args) { 11 Value: 4
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.start(); // Start thread t1


t2.start(); // Start thread t2
}
}
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the
Thread class. A thread begins its life inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread object.

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try { Thread 15 is running
// Displaying the thread that is running Thread 14 is running
System.out.println("Thread " + Thread.currentThread().getId() + " is running"); Thread 16 is running
} Thread 12 is running
catch (Exception e) { Thread 11 is running
// Throwing an exception Thread 13 is running
System.out.println("Exception is caught"); Thread 18 is running
} Thread 17 is running
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Multiprogramming and Multitasking

Both Multi-programming and Multi-tasking are related to Operating Systems Concepts .


CPU is a super fast device and keeping it occupied for a single task is never a good idea.
Considering the huge differences between CPU speed and IO speed, many concepts like multiprogramming,
multitasking, multithreading, etc have been introduced to make better CPU utilization.

Multiprogramming:-
Multi-programming increases CPU utilization by organizing jobs (code and data) so that the CPU always has one
to execute.
The idea is to keep multiple jobs in main memory. If one job gets occupied with IO, CPU can be assigned to
other job.
Multi-tasking:-
Multi-tasking is a logical extension of multiprogramming.
ability of an OS to execute more than one task simultaneously on a CPU machine.
These multiple tasks share common resources (like CPU and memory).
In multi-tasking systems, the CPU executes multiple jobs by switching among them typically using a small
time quantum, and the switches occur so quickly that the users feel like interact with each executing task at
the same time.
Types of Multitasking:
• Process-based Multitasking: Multiple processes run concurrently. Each process
has its own memory space.
• Thread-based Multitasking: Multiple threads within the same process are
executed concurrently, as described in the multithreading section.

Example: Consider running multiple Java programs or scripts on your machine. Each
program is a separate process, and the operating system manages their execution.

Example Scenario:
• You have a Java-based server running in the background.
• Simultaneously, you run another Java program for data analysis.
• Both programs are independent processes that run concurrently, showcasing
process-based multitasking.
Thread Class in Java

▪ Thread is a line of execution within a program.


▪ Each program can have multiple associated threads.
▪ Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a
thread class that has various method calls in order to manage the behavior of threads by providing constructors and
methods to perform operations on threads.
Ways of creating threads
Creating own class which is extending to parent Thread class
Implementing the Runnable interface.

// Way 1 // Creating thread By Extending To Thread class


import java.io.*;
import java.util.*;
class MyThread1 extends Thread {
public void run() {
System.out.println("This Thread is running created by extending to parent Thread class");
}
// Method 2 // Main driver method
public static void main(String[] args) {
MyThread1 myThread = new MyThread1();
myThread.start();
}
}
Sample code to create Threads by Extending Thread Class:
import java.io.*;
import java.util.*;

public class GFG1 extends Thread {


// initiated run method for Thread
public void run()
{
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{
GFG1 g1 = new GFG1();

// Invoking Thread using start() method


g1.start();
}
}
Sample code to create Thread by using Runnable Interface:

import java.io.*;
import java.util.*;

public class GFG implements Runnable {


// method to start Thread
public void run()
{
System.out.println( "Thread is Running Successfully");
}

public static void main(String[] args)


{
GFG g1 = new GFG();
// initializing Thread Object
Thread t1 = new Thread(g1);
t1.start();
}
}
Thread Class in Java

A thread is a program that starts with a method() frequently used in this class only known
as the start() method.
This method looks out for the run() method which is also a method of this class and
begins executing the body of the run() method. Here, keep an eye over the sleep() method.

Every class that is used as thread must implement Runnable interface and over ride it’s run method.

SYNTAX

public class Thread extends Object implements Runnable


Constructors of this class are as follows:
Methods of Thread class:
Also do remember there are certain methods inherited from class java. lang.Object that
are as follows:
• equals() Method
• finalize() Method
• getClass() Method
• hashCode() Method
• notify() Method
• notifyAll() Method
• toString() Method
• wait() Method
// Java program demonstrating different constructors of the Thread class

public class ThreadConstructorsDemo {

// Custom Runnable class


static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}

public static void main(String[] args) {

// 1. Thread() - Allocates a new Thread object with a default name


Thread thread1 = new Thread();
thread1.setName("Default Thread");
thread1.start();

// 2. Thread(Runnable target) - Allocates a new Thread object with a Runnable target


Runnable runnableTask = new MyRunnable();
Thread thread2 = new Thread(runnableTask);
thread2.start();
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"java.lang.ThreadGroup.getName()" because the return value of
"java.lang.Thread.getThreadGroup()" is null
at Threadcon.main(Threadcon.java:41)
Thread-2 is running
Runnable Thread is running
Thread-1 is running
Group Runnable Thread is running
Java JDBC
• JDBC stands for Java Database Connectivity.
• JDBC is a Java API to connect and execute the query with the database.
• it is a part of JavaSE (Java Standard Edition).
• JDBC API uses JDBC drivers to connect with the database.

There are four types of JDBC drivers:


DBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver

We can use JDBC API to access tabular data stored in any relational database.
By the help of JDBC API, we can save, update, delete and fetch data from the database.
It is like Open Database Connectivity (ODBC) provided by Microsoft.
Components of JDBC

There are generally four main components of JDBC through which it can interact with a database.

1. JDBC API: It provides various methods and interfaces for easy communication with the database.
It provides two packages as follows, which contain the java SE and Java EE platforms to exhibit WORA(write
once run anywhere) capabilities.
The java.sql package contains interfaces and classes of JDBC API.

2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a
database. It is used to make a database-specific call to the database to process the user request.

3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by
JDBC Drivers.

4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the JDBC
method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native
library to access ODBC characteristics.
Architecture of JDBC
Application: It is a java applet or a servlet that communicates with a data source.

The JDBC API: The JDBC API allows Java programs to execute SQL statements and
retrieve results.
Some of the important interfaces defined in JDBC API are as follows: Driver interface ,
ResultSet Interface , RowSet Interface , PreparedStatement interface, Connection inteface,
and cClasses defined in JDBC API are as follows: DriverManager class, Types class, Blob
class, clob class.

DriverManager: It plays an important role in the JDBC architecture. It uses some


database-specific drivers to effectively connect enterprise applications to databases.

JDBC drivers: To communicate with a data source through JDBC, you need a JDBC
driver that intelligently communicates with the respective data source.
//Java program to implement a simple JDBC application
package com.vinayak.jdbc; // Obtain a statement
Statement st = con.createStatement();
import java.sql.*;
// Execute the query
public class JDBCDemo { int count = st.executeUpdate(query);
System.out.println(
public static void main(String args[]) "number of rows affected by this query= "
throws SQLException, ClassNotFoundException + count);
{
String driverClassName= "sun.jdbc.odbc.JdbcOdbcDriver"; // Closing the connection as per the
String url = "jdbc:odbc:XE"; // requirement with connection is completed
String username = "scott"; con.close();
String password = "tiger"; }
String query = "insert into students values(109, 'bhatt')"; } // class

// Load driver class


Class.forName(driverClassName);

// Obtain a connection
Connection con = DriverManager.getConnection(
url, username, password);
SQL
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987

SQL commands are extensively used to interact with databases, enabling users to perform a wide range of actions
on database systems. Understanding these commands is crucial for effectively managing and manipulating data.

SQL Commands are mainly categorized into five categories:


I. DDL – Data Definition Language
II. DQL – Data Query Language
III. DML – Data Manipulation Language
IV. DCL – Data Control Language
V. TCL – Transaction Control Language
DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL commands that can be used to define the database
schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of
database objects in the database.
DQL (Data Query Language)
DQL statements are used for performing queries on the data within schema objects. The purpose of the DQL Command
is to get some schema relation based on the query passed to it.

DML (Data Manipulation Language)


The SQL commands that deal with the manipulation of data present in the database belong to DML or Data
Manipulation Language and this includes most of the SQL statements.
MYSQL COMMAND :

mysql --version
mysql –h localhost –P 3306 –u root –p

show databases;
create database oracle;
use oracle;
create table emp (dept int, Ename varchar(100), Job varchar(100), Sal int,Comm int);
insert into emp values(1, ‘queen’, ‘manager’, 1000, null);
insert into emp values(2, ‘king’, ‘chairman’, 1000, null);
select * from emp;

//to get stable connection in vscode


create user ‘hi’@’%’ identified with mysql_native_password by ‘1234’;
grant all privileges on *.* to ‘hi’@’%’;
flush privileges;
A Graphical User Interface (GUI) Based
Programming Paradigm
A Graphical User Interface (GUI) Based Programming Paradigm refers to a programming approach where
interaction with the program occurs through graphical elements like windows, buttons, text fields, etc., instead of
command-line or text-based inputs.
GUI programs are event-driven, meaning the program responds to user actions, such as clicks or key presses, in
real-time.

Key Concepts of GUI Programming:


1.Event-Driven: The program reacts to user actions (like mouse clicks, keyboard presses).
2.Widgets: These are the graphical components like buttons, labels, and text fields.
3.Layout Management: Positioning widgets in a window.
4.Graphical Frameworks: Libraries or toolkits like Swing, JavaFX, PyQt, etc., are used to create GUIs.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleGUI {


public static void main(String[] args) {
// Create a new JFrame (window)
JFrame frame = new JFrame("My GUI Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a button
JButton button = new JButton("Click Me");

// Add action listener to respond to button clicks


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Show a message when the button is clicked
JOptionPane.showMessageDialog(null, "Button Clicked!");
}
});
Explanation:
JFrame: A window where components (buttons, labels) are added.
JButton: A button component that can be clicked.
ActionListener: An interface used to define what happens when an action occurs (like a button click).
JOptionPane: A simple pop-up dialog to show messages.

Steps in GUI Programming:


Create GUI Components (e.g., buttons, text fields).
Attach Event Handlers (e.g., listening to button clicks).
Design the Layout of components inside the window.
Display the GUI and handle user actions.
Develop a java project dissertation based on the programming paradigm .

Here’s a sample structure and guide for a Java project dissertation based on programming paradigms.
The dissertation could explore Object-Oriented Programming (OOP), Functional Programming (FP), or other paradigms. I
will use OOP as the central focus, as Java is primarily an OOP language.

Title:
Exploring Object-Oriented Programming Paradigm in Java
Abstract
This dissertation explores the Object-Oriented Programming (OOP) paradigm within Java development. The project
focuses on key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction. A Java project will
be used to demonstrate the practical application of these principles through the development of a simple system, such as
a library management system. This work aims to show how Java's OOP capabilities make software design more
modular, maintainable, and scalable.
Table of Contents
1. Introduction
2. Literature Review
3. Overview of Object-Oriented Programming
4. Project Implementation
1. Project Description
2. System Design
3. Class Structure and Hierarchy
4. Inheritance and Polymorphism in Action
5. Encapsulation and Abstraction in Action
5. Testing and Evaluation
6. Conclusion
7. Future Work
8. References
9. Appendix
1. Introduction
The introduction will present the purpose of the dissertation and provide background on
programming paradigms, specifically focusing on OOP. Java will be introduced as a
prominent OOP language used in real-world applications. The objective of the project will
be outlined, such as building a library management system.
Problem Statement
The complexity of real-world software demands a modular approach to make systems
scalable and maintainable. The OOP paradigm facilitates this by focusing on creating
objects that represent real-world entities.
Objectives
To demonstrate the principles of OOP in Java.
To create a simple Java-based library management system.
To evaluate the benefits of OOP such as modularity, reusability, and maintainability.
2. Literature Review
This section will cover a review of existing programming paradigms with an emphasis
on OOP. It will explore the historical evolution of programming paradigms and discuss
how OOP has become a dominant approach, especially in Java. You can compare OOP
with procedural programming and functional programming in this section.
Key References:
•Books like "Effective Java" by Joshua Bloch.
•Research papers on the impact of OOP in large software systems.
•Comparative analysis of OOP and other paradigms.

3. Overview of Object-Oriented Programming


This chapter explains the core principles of OOP and how they are implemented in Java.
Principles of OOP:
•Encapsulation: Bundling of data and methods operating on the data within a single unit (class).
•Inheritance: Mechanism where one class inherits the properties and methods of another.
•Polymorphism: Ability to process objects differently based on their data type or class.
•Abstraction: Hiding implementation details from the user, exposing only the necessary parts.
4. Project Implementation
This section details the development of a Java project, demonstrating OOP principles. For
example, we could develop a Library Management System.
4.1 Project Description
The system will manage books, members, and transactions (issuing and returning books). It
will use OOP principles to model real-world entities (books, library members, etc.).
4.2 System Design
•Class Diagram: Visual representation of the system, including relationships between classes
(inheritance, association, etc.).
•UML Diagrams: Show how different classes interact.

4.3 Class Structure and Hierarchy


The project will include classes like Book, Member, Librarian, Transaction, etc. Each will
demonstrate different OOP principles.
// Inheritance Example
// Example of Encapsulation and Inheritance public class Member {
public class Book { private String name;
private String title; private int memberId;
private String author; private int maxBooksAllowed;
private boolean isAvailable;
public Member(String name, int memberId) {
public Book(String title, String author) { this.name = name;
this.title = title; this.memberId = memberId;
this.author = author; this.maxBooksAllowed = 5;
this.isAvailable = true; }
} // Methods for issuing and returning books
}
public void issueBook() {
this.isAvailable = false; public class PremiumMember extends Member {
} public PremiumMember(String name, int
public void returnBook() { memberId) {
this.isAvailable = true; super(name, memberId);
} this.maxBooksAllowed = 10; // Overriding
public boolean isAvailable() { max book limit for premium members
return isAvailable; }
} }
}
4.4 Inheritance and Polymorphism in Action
Inheritance will be used to show the relationship between classes like Member and
PremiumMember. Polymorphism can be demonstrated with method overloading and
overriding.
4.5 Encapsulation and Abstraction in Action
Encapsulation is demonstrated by keeping attributes private and providing
getter/setter methods. Abstraction is achieved by hiding implementation details in the
library system (e.g., issuing a book hides the detailed transaction process).

5. Testing and Evaluation


This section will describe the testing process for the Java project and evaluate the results.
Unit testing tools like JUnit can be used to test different components of the system.
5.1 Unit Testing
Test cases will be written for classes like Book and Member. The effectiveness of OOP
will be analyzed in terms of code maintainability, scalability, and testability.
import static org.junit.Assert.*;
import org.junit.Test;

public class BookTest {

@Test
public void testBookAvailability() {
Book book = new Book("Java Programming", "Author Name");
assertTrue(book.isAvailable());

book.issueBook();
assertFalse(book.isAvailable());
}
}
5.2 Evaluation Criteria
Code reusability through inheritance.
Flexibility with polymorphism.
System maintainability due to modular class structure.

6. Conclusion
This section summarizes the key findings of the project. It highlights how Java’s OOP features contribute to creating
maintainable, modular, and scalable applications. The dissertation will conclude that Java’s OOP capabilities can
efficiently model real-world problems in software.

7. Future Work
Future work could focus on extending the project by adding more advanced OOP features, like interfaces and design
patterns. The system could be scaled to include more complex real-world scenarios, such as handling multiple
libraries.

8. References
List academic references, textbooks, Java documentation, and research papers used in the dissertation.
9. Appendix
This section will include the complete source code of the project, screenshots of
the system in action, and additional UML diagrams if necessary.

This structure provides a comprehensive approach for a Java project dissertation based on
the programming paradigm, with a focus on OOP.
JAVA SWING

Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT].
// Java program using label (swing)
// to display the message “GFG WEB Site Click”
import java.io.*;
import javax.swing.*;
// Main class
class swingg {
// Main driver method
public static void main(String[] args)
{
// Creating instance of JFrame
JFrame frame = new JFrame();
// Creating instance of JButton
JButton button = new JButton(" GFG WebSite Click");
// x axis, y axis, width, height
button.setBounds(150, 200, 220, 50);
// adding button in JFrame
frame.add(button);
// 400 width and 500 height
frame.setSize(500, 600);
// using no layout managers
frame.setLayout(null);
// making the frame visible
frame.setVisible(true);}}
// Java program to create three buttons
// with caption OK, SUBMIT, CANCEL
import java.awt.*;
class button {
button()
{ Frame f = new Frame();
// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);
// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);
// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
JAVA SWING
MVC

The Model-View-Controller (MVC) is a well-known design pattern in the web


development field.
It is way to organize our code. It specifies that a program or application shall consist
of data model, presentation information and control information.
The MVC pattern needs all these components to be separated as different objects.
MVC
The MVC pattern architecture consists of three layers:
Model: It represents the business layer of application. It is an object to carry the data that can also contain the logic to
update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the data that the model contains.
Controller: It works on both the model and view. It is used to manage the flow of application, i.e. data flow in the model
object and to update the view whenever data is changed.

You might also like