APP Unit 3
APP Unit 3
Unit-3
Advanced Java Programming Paradigms
Outline of the Presentation
• Computing systems model the world, and the world contains actors that execute independently of, but communicate with,
each other. In modelling the world, many (possibly) parallel executions have to be composed and coordinated, and that's
where the study of concurrency comes in.
• There are two common models for concurrent programming: shared memory and message passing.
• Shared memory. In the shared memory model of concurrency, concurrent modules interact by reading and writing
shared objects in memory.
• Message passing. In the message-passing model, concurrent modules interact by sending messages to each other
through a communication channel. Modules send off messages, and incoming messages to each module are queued up
for handling
Issues Concurrent Programming Paradigm
Concurrent programming is programming with multiple tasks. The major issues of concurrent programming are:
• Sharing computational resources between the tasks;
• Interaction of the tasks.
Objects shared by multiple tasks have to be safe for concurrent access. Such objects are called protected. Tasks accessing such an
object interact with each other indirectly through the object.
An access to the protected object can be:
• Lock-free, when the task accessing the object is not blocked for a considerable time;
• Blocking, otherwise.
Blocking objects can be used for task synchronization. To the examples of such objects belong:
• Events;
• Mutexes and semaphores;
• Waitable timers;
• Queues
Multithreaded Programming
• For example, process-based multitasking enables you to run the Java compiler at the
same time that you are using a text editor.
• For instance, a text editor can format text at the same time that it is printing, as long
as these two actions are being performed by two separate threads.
• Thus, process-based multitasking deals with the “big picture,” and thread-based
multitasking handles the details.
Thread Class and the Runnable Interface
• Java’s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable. Thread encapsulates a thread of execution.
• The Thread class defines several methods that help manage threads.
Main Thread
• When a Java program starts up, one thread begins running immediately. This is
• usually called the main thread of your program, because it is the one that is executed
• when your program begins. The main thread is important for two reasons:
■ Often it must be the last thread to finish execution because it performs various
shutdown actions.
Main Thread (Continue…)
• Main thread is created automatically when your program is started, it can be controlled
through a Thread object.
• This method returns a reference to the thread in which it is called. Once you have a
reference to the main thread, you can control it just like any other thread.
Example: • In this program, a reference to the current thread (the main thread, in this
case) is obtained by calling currentThread( ), and this reference is stored
in the local variable t.
• Next, the program displays information about the thread. The program then
calls setName( ) to change the internal name of the thread. Information
about the thread is then redisplayed.
• Next, a loop counts down from five, pausing one second between each line.
The pause is accomplished by the sleep( ) method.
• This would happen if some other thread wanted to interrupt this sleeping
one.
Output
Creating a Thread
• In the most general sense, you create a thread by instantiating an object of type
Thread.
• Java defines two ways in which this can be accomplished:
■ You can implement the Runnable interface.
■ You can extend the Thread class, itself.
Example that creates a new thread and starts it running
Output
Extending Thread
• The second way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class.
• The extending class must override the run( ) method, which is the entry point for the
new thread. It must also call start( ) to begin execution of the new thread.
Output
Using is Alive( ) and join( )
• The main thread to finish last. In the preceding examples, this is accomplished by calling sleep( )
within main( ), with a long enough delay to ensure that all child threads terminate prior to the
main thread.
• Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the
thread. This method is defined by Thread, and its general form is shown here:
• The isAlive( ) method returns true if the thread upon which it is called is still running. It returns
false otherwise.
• While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a
thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException
Example
Example
Output
Thread Priorities
• Thread priorities are used by the thread scheduler to decide when each thread should be allowed to
run.
• To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its
general form:
• Here, level specifies the new priority setting for the calling thread. The value of level must be within
the range MIN_PRIORITY and MAX_PRIORITY.
• Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities are defined as final variables within Thread.
• You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown
here:
This package provides classes and interfaces to perform most of the JDBC functions like
creating and executing SQL queries.
javax.sql package
• It is a JDBC extension API and provides server-side data
access and processing in Java Program.
Load Driver
1.Class.forName()
2.DriverManager.registerDriver()
Class.forName()
In this way, the driver’s class file loads into the memory
at runtime. It implicitly loads the driver. While loading, the
driver will register with JDBC automatically.
DriverManager.registerDriver()
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())
Establish Connection
After loading the driver, the next step is to create and establish the
connection. Once required, packages are imported and drivers are loaded
and registered, then we can go for establishing a Database connection.
DriverManager class has the getConnection method, we will use this
method to get the connection with Database.
To call getConnection() method, we need to pass 3 parameters. The 3
parameters are string data type URL, a username, and a password to
access the database.
• The getConnection() method is an overloaded method. The 2
methods are:
• getConnection(URL,username,password); – It has 3 parameters
URL, username, password.
• getConnection(URL); – It has only one parameter. URL has a
username and password also.
Establish Connection
The following table lists the JDBC connection strings for the different databases:
Example:
Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost
:1521:xe,System,Pass123@)
Once the connection has established, we can interact with the connected Database. First,
we need to create the statement to perform the SQL query and then execute the
statement.
There are 3 statement interfaces are available in the java.sql package. These are
explained below:
a) Statement
This interface is used to implement simple SQL statements with no parameter. It returns
the ResultSet object.
c) execute(String sql)
The execute() method is used to execute the SQL query. It returns true if it
executes the SELECT query. And, it returns false if it executes INSERT or
UPDATE query.
d) executeBatch()
This method is used to execute a batch of SQL queries to the Database and
if all the queries get executed successfully, it returns an array of update
counts. We will use this method to insert/update the bulk of records .
Retrieve Results
• When we execute the queries using the executeQuery() method, the result will be stored
in the ResultSet object.
• The returned ResultSet object will never be null even if there is no matching record in the
table. ResultSet object is used to access the data retrieved from the Database.
ResultSet rs 1= statemnt1.executeQuery(QUERY));
• The executeQuery() method for the SELECT query. When someone tries to execute the
insert/update query, it will throw SQLExecption with the message “executeQuery
method can not be used for update”.
• A ResultSet object points to the current row in the Resultset. To iterate the data in the
ResultSet object, call the next() method in a while loop. If there is no more record to
read, it will return FALSE.
• ResultSet can also be used to update data in DB. We can get the data from ResultSet
using getter methods such as getInt(), getString(), getDate(). We need to pass the column
index or column name as the parameter to get the values using Getter methods.
Close Connection
• To close the JDBC connection. need to make sure that we have closed the resource after
we have used it. If we don’t close them properly we may end up out of connections.
• When we close the connection object, Statement and ResultSet objects will be closed
automatically.
conn.close();
• From Java 7 onwards, we can close the JDBC connections automatically using a try-catch
block. JDBC connection should be opened in the parenthesis of the try block. Inside the
try block, you can do the database connections normally as we do.
• Once the execution exits the try block, it will automatically close the connection. In this
case, we don’t need to close the connection by calling conn.close method in the Java
program.
try(Connection conn = DriverManager.getConnection(url, user, password))
{
//database connection and operation
}
Java JDBC Connection Example
Implement the 6 basic steps to connect with database using JDBC in Java program.
Create Table
• Before that, first, create one table and add some entries into it.
• Below is the SQL query to create a table.
create table employee_details (empNum number(10), lastName varchar(50), firstName varchar(50), email
varchar(255) , deptNum number(10), salary number(10));
import java.sql.*; //Get the values of the record using while loop
while(rs1.next())
public class Sample_JDBC_Program {
{
public static void main(String[] args) throws int empNum = rs1.getInt("empNum");
ClassNotFoundException, SQLException { String lastName = rs1.getString("lastName");
// store the SQL statement in a string String firstName = rs1.getString("firstName");
String QUERY = "select * from employee_details“ String email = rs1.getString("email");
String deptNum = rs1.getString("deptNum");
//register the oracle driver with DriverManager
String salary = rs1.getString("salary");
Class.forName("oracle.jdbc.driver.OracleDriver"); //store the values which are retrieved using ResultSet and print it
/*Here we have used Java 8 so opening the connection in try System.out.println(empNum + "," +lastName+ "," +firstName+ ","
statement*/ +email +","+deptNum +"," +salary);
try(Connection conn = }
}
DriverManager.getConnection("jdbc:oracle:thin:system/pass123 }
@localhost:1521:XE")) catch (SQLException e) {
{ //If exception occurs catch it and exit the program
Statement statemnt1 = conn.createStatement(); e.printStackTrace();
}
//Created statement and execute it
}
ResultSet rs1 = statemnt1.executeQuery(QUERY); }
{
Java Program - Mysql
import java.sql.*;
public class javamysql {
public static void main(String arg[])
{ Connection connection = null;
try {
// below two lines are used for connectivity.
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","mydbuser", "mydbuser");
// mydb is database; mydbuser is name of database ;mydbuser is password of database
Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery("select * from designation");
int code;
String title;
while (resultSet.next()) {
code = resultSet.getInt("code");
title = resultSet.getString("title").trim();
System.out.println("Code : " + code + " Title : " + title);
}
resultSet.close();
statement.close();
connection.close();
}
catch (Exception exception) {
System.out.println(exception);
}
}
}
JAVA APPLETS
Learning Objectives:
• Introduction
CUI (Character User Interface)
GUI (Graphical User Interface)
Abstract Window Toolkit (AWT)
Whenever the end-user compile the program, can enter two numbers in the given space and clicking on the “equal button”, can
get the results in the specified space, which is easy to understand. This is an example for GUI for addition of two numbers.
JAVA APPLETS
• Graphical User Interface (GUI)
Java Abstract Window Toolkit (AWT) is an Application Program Interface (API) to develop GUI or window-based
application in java. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous classes and methods that
allow you to create and manage the GUI window.
• Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web
browser or an applet viewer.
• Execution of an applet does not begin at main( ) [In other words, there is no main() method in an Applet]. Output to
your applet’s window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as
drawString( ), which outputs a string to a specified X,Y location. Input is also handled differently than in an application.
• Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by
a Java-enabled web browser when it encounters the APPLET tag within the HTML file.
• To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that
contains the APPLET tag.
JAVA APPLETS
Java applets are one of three kinds of Java programs:
• An application is a standalone program that can be invoked from the command line.
• A servlet is a program that is invoked on demand on a server program and that runs in
the context of a web server process.
JAVA APPLETS
• Applets are programs stored on a web server, like web pages.
• When an applet is referred to in a web page that has been fetched and processed by a browser, the browser
generates a request to fetch (or download) the applet program, then executes the program in the browser’s
execution context, on the client host.
s e r ve r ho s t
br o w s e r ho s t
we b s e rv e r
bro ws e r
re qe u s t fo r
m y W e bPa g e .h tm l
m y W e bPa g e .h tm l
m y W e bPa g e .h tm l H e llo W o rld.cla s s
... re qu e s t fo r
< a pple t co de = H e llo W o rld.cla s s < /a pple t> H e llo W o rldcla s s
...
H e llo W o rld.cla s s H e llo W o rld.cla s s
JAVA APPLETS
Life Cycle of an Applet
It's essential in understanding the sequence whereby the
different methods indicated in the figure are invoked. The
following methods are called in this order when an applet
begins:
1.init( )
2.start( )
3.paint( )
4.stop( )
5.destroy( )
JAVA APPLETS
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only
once.
• public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.
Within the method paint() we will call the drawString() method to print a
text message in the applet window.
JAVA APPLETS
Types of Applets in Java
1.Local Applet
2.Remote Applet
Local Applet
• Local Applet is developed locally and stored in the local system. A web page doesn't need the get the information
from the internet when it finds the local Applet in the system. It is specified or defined by the file name or pathname.
There are two attributes used in defining an applet, i.e., the codebase that specifies the path name and code that
defined the name of the file that contains Applet's code..
• Example:
<applet
codebase = “MyOwnApplet
"
code = “FirstApplet.class"
width = 120
height = 120>
</applet>
JAVA
JAVA APPLETS
APPLETS
Remote Applet
• Remote applets are stored in a remote computer and an Internet connection is needed to access them. The remote
applet is designed and developed by other developers. To find and load a remote applet, you need to know the
address of the network applet, i.e., the Uniform Resource Locator (URL).
• Example:
<applet
codebase = "http://www.myconnect.com/
applets/"
code = "FirstApplet.class"
width = 120
height =120>
</applet>
JAVA
JAVA APPLETS
APPLETS
Difference between Local Applet and Remote Applet:
There is no need to define the Applet's URL We need to define the Applet's URL in
in Local Applet. Remote Applet.
Local Applet is available on our computer. Remote Applet is not available on our
computer.
To use it or access it, we don't need Internet To use it or access it on our computer, we
Connection. need an Internet Connection.
It is written on our own and then embedded It was written by another developer.
into the web pages.
We don't need to download it. It is available on a remote computer, so we
need to download it to our system.
JAVA
JAVA APPLETS
APPLETS
How to run an applet
An applet can be run two ways:
1.Through HTML file.
2.Using the appletviewer tool (for testing purposes).
1. Through HTML file:
For an applet to run in a web browser, we must write a short HTML text file that
contains a tag to load an applet. For this, we can use <applet> or <object> tags. The
HTML <applet> tag specifies an applet. It embeds Java applets in HTML documents. It
does not support HTML5.
JAVA
JAVA APPLETS
APPLETS
Through HTML file:
<!DOCTYPE html>
<html>
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code = “FirstApplet.class" width = "300" height =
"200"></applet>
</body>
</html>
• In the HTML text file above, the code attribute of the <applet> tag specifies the applet class to execute.
• The width and height attributes are also required. They define the initial size of the panel on which the
applet is running.
• The applet command must be closed with the </applet> tag.
JAVAAPPLETS
JAVA APPLETS
Below is the applet class embedded in the HTML file above:
import java.applet.*;
import java.awt.*;
Output:
JAVA
JAVA APPLETS
APPLETS
Sample Applet Program-3
• Text Fields
Text area
Labels
Checkboxes
Buttons
Lists
Drawing areas
Menus
Containers
JAVA
JAVA APPLETS
APPLETS
EVENT HANDLING
The pathway to efficient applet programming is how to handle events. The majority of events to which the applet will react
come from the user. The most frequent various types of events processed involve those triggered by the keyboard, mouse, and
various controllers, including push buttons. Events are supported by the java.awt.event package.
Steps to perform Event Handling
• Register the component with the Listener
• Registration Methods
• For registering the component with the Listener, many classes provide the registration methods.
Disadvantages of applets
• The client browser requires a plugin to run the applet.
• The mobile browser on iOS or Android does not run any Java applets. Desktop browsers have dropped
support for Java applets along with the rise of mobile operating systems.
JFC stands for Java Foundation Classes, a set of classes used to create graphical
user interfaces (GUIs) and add rich graphical features and interactivity to Java
applications.
The JTextField renders an editable single-line text box. Users can input non-formatted text in the
box.
Can initialize the text field by calling its constructor and passing an optional integer parameter.
This parameter sets the box width measured by the number of columns.
Also, it does not limit the number of characters that can be input into the box.
Syntax:
JTextField txtBox = new JTextField(50);
It is the most widely used text component.
It has three constructors:
1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)
JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package
javax.swing.JTextArea class. It is used for displaying multiple-line text.
Declaration:
public class JTextArea extends JTextComponent
Syntax:
JTextArea textArea_area=new JTextArea("Ninja! please write something in the text area.");
The JTextArea Contains four constructors. They are as follows:
1. JTextArea()
2. JTextArea(String s)
3. JTextArea(int row, int column)
4. JTextArea(String s, int row, int column)
Display:
JPasswordField
• In Java, the Swing toolkit contains a JPasswordField Class.
• It is under package javax.swing.JPasswordField class.
• It is specifically used for the password, and we can edit them.
Declaration:
public class JPasswordField extends JTextField
Syntax:
JPasswordField password = new JPasswordField();
The JPasswordFieldContains 4 constructors. They are as follows:
• JPasswordField()
• JPasswordField(int columns)
• JPasswordField(String text)
• JPasswordField(String text, int columns)
JTable
• In Java, the Swing toolkit contains a JTable Class.
• It is under package javax.swing.JTable class.
• It is used to draw a table to display data.
Syntax:
JTable table = new JTable(table_data, table_column);
The JTable contains two constructors. They are as follows:
1. JTable()
2. JTable(Object[][] rows, Object[] columns)
JList
• In Java, the Swing toolkit contains a JList Class.
• It is under package javax.swing.JList class.
• It is used to represent a list of items together.
• We can select one or more than one items from the list.
Declaration:
public class JList extends JComponent implements Scrollable, Accessible
Syntax:
DefaultListModel<String> list1 = new DefaultListModel<>();
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList<String> list_1 = new JList<>(list1);
The JListContains 3 constructors. They are as follows:
JList()
JList(ary[] listData)
JList(ListModel<ary> dataModel)
Display:
JOptionPane
In Java, the Swing toolkit contains a JOptionPane Class. It is under package javax.swing.JOptionPane class. It
is used for creating dialog boxes for displaying a message, confirm box, or input dialog box.
Declaration:
public class JOptionPane extends JComponent implements Accessible
Syntax:
JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night.");
Declaration:
public class JPopupMenu extends JComponent implements Accessible, MenuElement
Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");
• The Model-View-Controller (MVC) software design pattern is a method for separating concerns within a
software application.
• As the name implies, the MVC pattern has three layers:
• The Model defines the business layer of the application,
• the Controller manages the flow of the application,
• the View defines the presentation layer of the application.
Model: Handles data and business logic. Represents the business layer of the application
View: Presents the data to the user whenever asked for. Defines the presentation of the application
Controller: Entertains user requests and fetch necessary resources. Manages the flow of the application
Each of the components has a demarcated set of tasks which ensures smooth functioning of the entire
application along with complete modularity.
Model-View-Controller
Model :
• Model is where the application’s data objects are stored. It represents knowledge as a structure of
objects.
• The model doesn’t know anything about views and controllers but it can contain logic to update
controller if its data changes.
• The model is quite simply the data for our application.
• The data is “modelled” in a way it’s easy to store, retrieve, and edit.
• The model is how we apply rules to our data, which eventually represents the concepts our
application manages.
• For any software application, everything is modelled as data that can be handled easily.
• What is a user, a book, or a message for an app? Nothing really, only data that must be processed
according to specific rules. Like, the date must not be higher than the current date, the email must be
in the correct format, the name mustn’t be more than “x” characters long, etc.
Model-View-Controller
Model:
• Whenever a user makes any request from the controller, it contacts the appropriate model which
returns a data representation of whatever the user requested.
• This model will be the same for a particular work, irrespective of how we wish to display it to the
user.
• That is why we can choose any available view to render the model data.
• Additionally, a model also contains the logic to update the relevant controller whenever there is
any change in the model’s data.
Model-View-Controller
VIEW:
• The view determines how the component is displayed on the screen, including any aspects of the view that
are affected by the current state of the model.
• View can also update the model by sending appropriate messages. Users interact with an application through
its View.
• As the name suggests, the view is responsible for rendering the data received from the model. There may be
pre-designed templates where you can fit the data, and there may even be several different views per model
depending on the requirements.
• Any web application is structured keeping these three core components in mind. There may be a primary
controller that is responsible for receiving all the requests and calling the specific controller for specific
actions.
Model-View-Controller
CONTROLLER:
• The controller determines how the component reacts to the user.
• Example : When the user clicks a check box, the controller reacts by changing the model to reflect the user’s
choice (checked or unchecked).
• The controller is like housekeeper of the application – it performs coordination between model and view to
entertain a user request. The user requests are received as HTTP get or post request – for example, when the
user clicks on any GUI elements to perform any action.
• The primary function of a controller is to call and coordinate with the model to fetch any necessary resources
required to act.
• Usually, on receiving a user request, the controller calls the appropriate model for the task at hand.
Advantages of the MVC Architecture
• A common problem faced by application developers these days is the support for different type of
devices.
• The MVC architecture solves this problem as developers can create different interfaces for different
devices, and based on from which device the request is made, the controller will select an appropriate
view.
• The model sends the same data irrespective of the device being used, which ensures a complete
consistency across all devices.
• The MVC separation beautifully isolates the view from the business logic.
• It also reduces complexities in designing large application by keeping the code and workflow
structured.
• This makes the overall code much easier to maintain, test, debug, and reuse.
Model-View-Controller
• We are going to create a Student object acting as a model.
• StudentView will be a view class which can print student details on console
• StudentController is the controller class responsible for storing data in the Student object and updating
StudentView accordingly.
• MVCPatternDemo, our demo class, will use StudentController to demonstrate the use of MVC pattern.
Model-View-Controller
Step 1: Create the Model : public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Model-View-Controller
Step 2: Create the View
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
Widgets
• Graphical User Interface (GUI) elements are the visual components that allow users to interact with
software applications.
• These elements are often referred to as "widgets," which are essentially building blocks that make up
the user interface.
• Each widget serves a specific purpose and provides a way for users to input information, view data, or
trigger actions. Here is a list of controls in the javax.swing package
Input Components
• Buttons ( JButton, JRadioButtons, JCheckBox)
• Text (JTextField, JTextArea)
• Menus (JMenuBar, JMenu, JMenuItem)
• Sliders (JSlider)
• JComboBox (uneditable) (JComboBox)
• List (Jlist )
Widgets
Information Display Components
• JLabel
• Progress bars (JProgressBar)
• Tool tips (using JComponent's setToolTipText(s) method)
Choosers
• File chooser (JFileChooser)
• Color chooser (JColorChooser)
More complex displays
• Tables (JTable)
• Trees (JTree)