0% found this document useful (0 votes)
20 views51 pages

UNIT 3

Notes SRM SEM5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views51 pages

UNIT 3

Notes SRM SEM5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

UNIT 3

ADVANCED PROGRAMMING PARADIGM


Concurrent Programming Paradigm - Multithreading and Multitasking

Multithreading in Java is a process of executing multiple threads simultaneously.


• A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
• However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads takes less time than process.
• Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers, memory maps,
updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Thread
• A thread is a lightweight subprocess, the smallest unit of
processing. It is a separate path of execution.
• Threads are independent. If there occurs exception in one
thread, it doesn't affect other threads. It uses a shared memory
area.
• As shown in the above figure, a thread is executed inside the
process. There is context-switching between the threads. There
can be multiple processes inside the OS, and one process can
have multiple threads.
• Note: At a time one thread is executed only.
Java Thread class
• Java provides Thread class to achieve thread programming. Thread class provides constructors and
methods to create and perform operations on a thread. Thread class extends Object class and implements
Runnable interface.
• Java Thread Methods
S.N. Modifier and Type Method Description

1) Void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static Thread currentThread() It returns a reference to the currently executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.


S.N. Modifier and Type Method Description
11) boolean isAlive() It tests if the thread is alive.

It causes the currently executing thread object to pause and allow other threads to execute
12) static void yield()
temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and all of its subgroups.

17) boolean isDaemon() It tests if the thread is a daemon thread.

19) boolean isinterrupted() It tests whether the thread has been interrupted.

20) void interrupt() It interrupts the thread.

21) static boolean interrupted() It tests whether the current thread has been interrupted.

22) static int activeCount() It returns the number of active threads in the current thread's thread group.

23) void checkAccess() It determines if the currently running thread has permission to modify the thread.

24) static boolean holdLock() It returns true if and only if the current thread holds the monitor lock on the specified object.

25) static void dumpStack() It is used to print a stack trace of the current thread to the standard error stream.
26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements representing the stack dump of the thread.

27) static int enumerate() It is used to copy every active thread's thread group and its subgroup into the specified array.

28) Thread.State getState() It is used to return the state of the thread.

29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread belongs

It is used to return a string representation of this thread, including the thread's name, priority, and
30) String toString()
thread group.

31) void notify() It is used to give the notification for only one thread which is waiting for a particular object.

32) void notifyAll() It is used to give the notification to all waiting threads of a particular object.

33) void setContextClassLoa It sets the context ClassLoader for the Thread.
der()
34) ClassLoader getContextClassLoa It returns the context ClassLoader for the thread.
static der()
35) Thread.UncaughtExce getDefaultUncaugh It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
ptionHandler tExceptionHandler(
)
36) static void setDefaultUncaugh It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.
tExceptionHandler(
)
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


• New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code
has not been run yet and thus has not begun its execution.
• Active: When a thread invokes the start() method, it moves from the new state to the active state. The active
state contains two states within it: one is runnable, and the other is running.
• Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most
common change in the state of a thread is from runnable to running and again back to runnable.
• Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
• Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A)
has entered the critical section of a code and is not willing to leave that critical section. In such a
scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid
such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a
specific span of time, and not forever.
• Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
Different states involved in the life cycle of a thread
Implementation of Thread States
In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java
provides the constants ENUM to represent the state of a thread. These constants are:

1. public static final Thread.State NEW : It represents the first state of a thread that is the NEW state.

2. public static final Thread.State RUNNABLE : It represents the runnable state.It means a thread is waiting in the queue to run.

3. public static final Thread.State BLOCKED : It represents the blocked state. In this state, the thread is waiting to acquire a lock.

4. public static final Thread.State WAITING: It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting state is waiting for another thread to
complete its task.

5. public static final Thread.State TIMED_WAITING: It represents the timed waiting state. The main difference between waiting
and timed waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has the time constraint. A
thread invoking the following method reaches the timed waiting state.
 sleep
 join with timeout
 wait with timeout
 parkUntil
 parkNanos

6. public static final Thread.State TERMINATED: It represents the final state of a thread that is terminated or dead. A terminated
thread means it has completed its execution.
Java Threads | How to create a thread in Java

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

1. Thread class
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class
and implements Runnable interface.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
2. Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed
by a thread. Runnable interface have only one method named run().
public void run() - is used to perform action for a thread.
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the following
tasks:
 A new thread starts(with new callstack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.
Java Thread Example by extending Thread class
FileName: Multi.java

class Multi extends Thread{


public void run(){
System.out.println("thread is running..."); }
public static void main(String args[]){
Multi t1=new Multi();
t1.start(); } }
Output:
thread is running...
Java Thread Example by implementing Runnable interface
FileName: Multi3.java
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)

t1.start();
}
}
Output:
thread is running...
Declarative Programming Paradigm
Java Database Connectivity (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:
 JDBC-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.
A list of popular interfaces of JDBC API are given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface

A list of popular classes of JDBC API are given below:


 DriverManager class
 Blob class
 Clob class
 Types class
Why Should We Use JDBC
• Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
• We can use JDBC API to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
What is API
• API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.
Java Database Connectivity with 5 Steps

There are 5 steps to connect any java


application with the database using
JDBC. These steps are as follows:

 Register the Driver class


 Create connection
 Create statement
 Execute queries
 Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Syntax
public static void forName(String className)throws ClassNotFoundException

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password) throws SQLException

Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of statement
is responsible to execute queries with the database.
Syntax
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.
Syntax
public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.

Syntax
public void close()throws SQLException
Example
con.close();

Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to follow 5 following steps.
• In this example we are using MySql as the database. So we need to know following informations for the mysql
database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo
where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we
may also use IP address, 3306 is the port number and sonoo is the database name. We may use any
database, in such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
• Let's first create a table in the mysql database, but before creating table, we need to create database first.
create database sonoo;
use sonoo;
create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
To connect java application with the mysql database, mysqlconnector.jar file is required to be loaded.
Two ways to load the jar file:
1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath
1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath
There are two ways to set the classpath:
• temporary
• Permanent
How to set the temporary classpath
open command prompt and write:
C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.;
as C:\folder\mysql-connector-java-5.0.8-bin.jar
Graphical User Interface Based Programming Paradigm:
Java Applet
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.

Hierarchy of Applet
• As displayed in the diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component
class provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It
provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet
is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
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.
Java Plug-in software is responsible to manage the life cycle of an applet.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet
code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150); } }

myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for
testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150); } }
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified
width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and
height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified
width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
Example of Graphics in applet:

import java.applet.Applet;
import java.awt.*;
myapplet.html
public class GraphicsDemo extends Applet{ <html>
public void paint(Graphics g){ <body>
g.setColor(Color.red); <applet code="GraphicsDemo.cla
g.drawString("Welcome",50, 50); ss" width="300" height="300">
g.drawLine(20,30,20,300); </applet>
</body>
g.drawRect(70,100,30,30);
</html>
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} }
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is required to be displayed. The
java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw
the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax: public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
public URL getCodeBase(): is used to return the base URL.
Example of displaying image in applet:

import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg"); }
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this); } }

myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is
required to be moved.
myapplet.html
Example of animation in applet: <html>
<body>
import java.awt.*;
<applet code="DisplayImage.class" width="300"
import java.applet.*; height="300">
public class AnimationExample extends Applet { </applet>
Image picture; </body>
public void init() { </html>

picture =getImage(getDocumentBase(),"bike_1.gif"); }
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){} } } }
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example of event
handling in applet that prints a message by click on the button.

Example of EventHandling in applet:


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){ myapplet.html
<html>
tf=new TextField(); <body>
tf.setBounds(30,40,150,20); <applet code="EventApplet.class"
width="300" height="300">
b=new Button("Click"); </applet>
b.setBounds(80,150,60,50); </body>
add(b);add(tf); </html>
b.addActionListener(this);
setLayout(null); }
public void actionPerformed(ActionEvent e){
tf.setText("Welcome"); } }
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT
(Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox,
JMenu, JColorChooser etc.

Difference between AWT and Swing

N.O Java AWT Java Swing


1 AWT components are platform-dependent. Java swing components are platform-independent.

2 AWT components are heavyweight. Swing components are lightweight.


3 AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4 AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane
etc.

5 AWT doesn't follows MVC(Model View Controller) where model Swing follows MVC.
represents data, view represents presentation and controller acts as an
interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples


There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside
the main() method.
FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Simple example of Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
File: Simple2.java
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Model View Controller
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.
The model designs based on the MVC architecture follow MVC design pattern. The application logic is
separated from the user interface while designing the software using model designs.

The MVC pattern architecture consists of three layers:


o 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.
o View: It represents the presentation layer of application. It is used to visualize the data that the model
contains.
o 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.
In Java Programming, the Model contains the
simple Java classes, the View used to display
the data and the Controller contains the
servlets. Due to this separation the user
requests are processed as follows:
1. A client (browser) sends a request to the
controller on the server side, for a page.
2. The controller then calls the model. It gathers
the requested data.
3. Then the controller transfers the data retrieved
to the view layer.
4. Now the result is sent back to the browser
(client) by the view.
The advantages of MVC architecture :
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller) simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with massive code.
o The extending and testing of application is easier.

Implementation of MVC using Java


To implement MVC pattern in Java, we are required to create the following three classes.
o Employee Class, will act as model layer
o EmployeeView Class, will act as a view layer

EmployeeContoller Class, will act a controller layer


Employee.java
MVC Architecture Layers: // class that represents model
public class Employee {
// declaring the variables
1. Model Layer private String EmployeeName;
The Model in the MVC design pattern acts as a private String EmployeeId;
data layer for the application. It represents the private String EmployeeDepartment;
business logic for application and also the state of // defining getter and setter methods
application. The model object fetch and store the public String getId() {
model state in the database. Using the model layer,
return EmployeeId; }
public void setId(String id) {
rules are applied to the data that represents the this.EmployeeId = id; }
concepts of application. public String getName() {
return EmployeeName; }
public void setName(String name) {
this.EmployeeName = name; }
public String getDepartment() {
return EmployeeDepartment; }
public void setDepartment(String Department) {
this.EmployeeDepartment = Department; } }
2. View Layer EmployeeView.java
As the name depicts, view represents the // class which represents the view
visualization of data received from the model. public class EmployeeView {
The view layer consists of output of application
// method to display the Employee details
or user interface. It sends the requested data to public void printEmployeeDetails (String EmployeeNa
the client, that is fetched from model layer by me, String EmployeeId, String EmployeeDepartment)
controller. {
System.out.println("Employee Details: ");
System.out.println("Name: " + EmployeeName);

System.out.println("Employee ID: " + Employee


Id);
System.out.println("Employee Department: " +
EmployeeDepartment);
}
}
3. Controller Layer EmployeeController.java
// class which represent the controller
The controller layer gets the user public class EmployeeController {
requests from the view layer and // declaring the variables model and view
processes them, with the necessary private Employee model;
validations. It acts as an interface private EmployeeView view;
// constructor to initialize
between Model and View. The public EmployeeController(Employee model, EmployeeView view) {
requests are then sent to model for this.model = model;
data processing. Once they are this.view = view; }
// getter and setter methods
processed, the data is sent back to public void setEmployeeName(String name){
the controller and then displayed model.setName(name); }
on the view. public String getEmployeeName(){
return model.getName(); }
public void setEmployeeId(String id){
model.setId(id); }
public String getEmployeeId(){
return model.getId(); }
public void setEmployeeDepartment(String Department){
model.setDepartment(Department); }
public String getEmployeeDepartment(){
return model.getDepartment(); }
// method to update view
public void updateView() {
view.printEmployeeDetails(model.getName(), model.getId(), model.getDepartment());
} }
Main Class Java file
// main class controller.updateView();
public class MVCMain { }
public static void main(String[] args) {
private static Employee retriveEmployeeFromDatabase()
// fetching the employee record based on the employee_ {
id from the database Employee Employee = new Employee();
Employee model = retriveEmployeeFromDatabase(); Employee.setName("Anu");
Employee.setId("11");
// creating a view to write Employee details on console Employee.setDepartment("Salesforce");
EmployeeView view = new EmployeeView(); return Employee;
}
EmployeeController controller = new EmployeeController }
(model, view);
controller.updateView(); The MVCMain class fetches the employee data from the
method where we have entered the values. Then it pushes
//updating the model data those values in the model. After that, it initializes the view
controller.setEmployeeName("Nirnay"); (EmployeeView.java). When view is initialized, the
System.out.println("\ Controller (EmployeeController.java) is invoked and bind it
n Employee Details after updating: "); to Employee class and EmployeeView class. At last the
updateView() method (method of controller) update the
employee details to be printed to the console.
Thank you

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy