APP - Unit 3
APP - Unit 3
Unit-3
Advanced Java Programming Paradigms
APP Faculties
Department of Computational Intelligence
SRM Institute of Science and Technology
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
APP Faculties - CINTEL 8
20-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Multithreaded Programming
• Java provides built-in support for multithreaded programming.
• A multithreaded program contains two or more parts that can run concurrently. Each part
of such a program is called a thread, and each thread defines a separate path of execution.
Thus, multithreading is a specialized form of multitasking.
• A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature
that allows your computer to run two or more programs concurrently.
• For example, process-based multitasking enables you to run the Java compiler at the same time that
you are using a text editor.
• In process-based multitasking, a program is the smallest unit of code that can be dispatched by the
scheduler.
• 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.
• 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.
• 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 is created automatically when your program is started, it can be controlled through a
Thread object.
• To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public
static member of Thread. Its general form is:
• 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.
• 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.
• The argument to sleep( ) specifies the delay period in milliseconds. Notice the
try/catch block around this loop.
• This would happen if some other thread wanted to interrupt this sleeping one.
• 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.
Output
APP Faculties - CINTEL 17
20-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
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.
• 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:
Output
APP Faculties - CINTEL 23
20-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
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:
1. Class.forName()
2. DriverManager.registerDriver()
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())
Example:
Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost
:1521:xe,System,Pass123@)
There are 3 statement interfaces are available in the java.sql package. These are
explained below:
a) Statement
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
APP Faculties - CINTEL 38
20-09-2023 Dr.Maivizhi counts.
Assistant We will use
Professor this method to insert/update the bulk of records
/ CINTEL .
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.
Learning Objectives:
• Introduction
CUI (Character User Interface)
GUI (Graphical User Interface)
Abstract Window Toolkit (AWT)
• What are Applets in Java?
Applet Basics
Life Cycle of an Applet
Types of Applets in Java
How to run an Applet
Sample Applet Programs
Advantages and Disadvantages
Applet Features over HTML
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.
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor
APP Faculties - CINTEL / CINTEL 45
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.
• 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.
1.init( )
2.start( )
3.paint( )
1.stop( )
2.destroy( )
• 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.
• Example:
<applet
codebase = “MyOwnApplet"
code = “FirstApplet.class"
width = 120
height = 120>
</applet>
• Example:
<applet
codebase = "http://www.myconnect.com/appl
ets/"
code = "FirstApplet.class"
width = 120
height =120>
</applet>
20-09-202320-09-2023 APP Faculties
Dr.Maivizhi Assistant Professor - CINTEL
/ CINTEL 56
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.
<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.
import java.applet.*;
import java.awt.*;
//FirstApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class FirstApplet extends Applet
{ To run an applet using the appletviewer tool, write in the
public void paint(Graphics g) command prompt:
{
g.drawString("welcome to my first applet",10,50); c:\>javac FirstApplet.java
} c:\>appletviewer FirstApplet.java
} c:\>appletviewer FirstApplet.html
Output:
• Text Fields
∙ Text area
∙ Labels
∙ Checkboxes
∙ Buttons
∙ Lists
∙ Drawing areas
∙ Menus
∙ Containers
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.
Lightweight
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.
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
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);
20-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 88
The JListContains 3 constructors. They are as follows:
JList()
JList(ary[] listData)
JList(ListModel<ary> dataModel)
Display:
Declaration:
public class JPopupMenu extends JComponent implements Accessible, MenuElement
Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");
Each of the components has a demarcated set of tasks which ensures smooth functioning of the entire
application along with complete modularity.
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 99
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.
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 100
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.
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 101
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.
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor
APP Faculties / CINTEL
- CINTEL 102
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.
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 103
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.
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor
APP Faculties / CINTEL
- CINTEL 104
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.
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
APP Faculties - CINTEL 105
Model-View-Controller
Step 1: Create the Model :
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 106
Model-View-Controller
Step 2: Create the View
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor
APP Faculties / CINTEL
- CINTEL 107
Model-View-Controller
Step 3: Create the Controller
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view) {
this.model = model;
this.view = view;
}
public void setStudentName(String name){
model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 108
Model-View-Controller
Step 4: Create the main Java file
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor
APP Faculties / CINTEL
- CINTEL 109
Model-View-Controller
Step 5: Test the Result
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 110
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 )
20-09-2023
20-09-2023 APP Faculties
Dr.Maivizhi Assistant - CINTEL
Professor / CINTEL 111
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)
20-09-2023
20-09-2023 Dr.Maivizhi Assistant Professor
APP Faculties / CINTEL
- CINTEL 112