0% found this document useful (0 votes)
32 views

CONCURRENT PROGRAMMING

CONCURRENT PROGRAMMING

Uploaded by

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

CONCURRENT PROGRAMMING

CONCURRENT PROGRAMMING

Uploaded by

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

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.
S.N. Modifier and Type Method Description

1) Voi d s ta rt() It i s used to start the execution of the thread.

2) voi d run() It i s used to do a n action for a thread.

Java Thread class 3) s ta tic void s l eep() It s l eeps a thread for the s pecified amount of ti me.

• Java provides Thread class to 4) s tatic Thread currentThread() It returns a reference to the currently executing thread object.

achieve thread programming. 5) voi d joi n() It wa i ts for a thread to die.


Thread class provides constructors 6) i nt getPri ority() It returns the priority of the thread.
and methods to create and perform 7) voi d s etPri ority() It cha nges the priority of the thread.
operations on a thread. Thread class 8) Stri ng getNa me() It returns the name of the thread.
extends Object class and implements 9) voi d s etName() It cha nges the name of the thread.

Runnable interface. 10) l ong getId() It returns the i d of the thread.

• Java Thread Methods


11) bool ean i s Alive() It tes ts if the thread is a live.

It causes the currentl y executing thread object to pause and allow other threads
12) s ta tic void yi el d()
to execute temporarily.

13) voi d s us pend() It i s used to suspend the thread.

14) voi d res ume() It i s used to resume the suspended thread.

15) voi d s top() It i s used to stop the thread.

16) voi d des troy() It i s used to destroy the thread group a nd a ll of i ts s ubgroups.

17) bool ean i s Daemon() It tes ts if the thread is a daemon thread.


19) void interrupt() It interrupts the thread.
It tests whether the thread has been
20) boolean isinterrupted()
interrupted.
It tests whether the current thread has been
21) static boolean interrupted()
interrupted.
It returns the number of active threads in the
22) static int activeCount()
current thread's thread group.
It determines if the currently running thread
23) void checkAccess()
has permission to modify the thread.
It returns true if and only if the current thread
24) static boolean holdLock() holds the monitor lock on the specified
object.
It is used to print a stack trace of the current
25) static void dumpStack()
thread to the standard error stream.
It returns an array of stack trace elements
26) StackTraceElement[] getStackTrace()
representing the stack dump of the thread.
It is used to copy every active thread's thread
27) static int enumerate() group and its subgroup into the specified
array.
28) Thread.State getState() It is used to return the state of the thread.
It is used to return the thread group to which
29) ThreadGroup getThreadGroup()
this thread belongs
It is used to return a string representation of
30) String toString() this thread, including the thread's name,
priority, and thread group.
It is used to give the notification for only one
31) void notify() thread which is waiting for a particular
object.
It is used to give the notification to all waiting
32) void notifyAll()
threads of a particular object.
33) void setContextClassLoader() It sets the context ClassLoader for the Thread.
It returns the context ClassLoader for the
34) ClassLoader getContextClassLoader()
thread.
It returns the default handler invoked when a
35) static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() thread abruptly terminates due to an
uncaught exception.
It sets the default handler invoked when a
36) static void setDefaultUncaughtExceptionHandler() thread abruptly terminates due to an
uncaught exception.
• 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.
• The following diagram shows the 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
1. 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 Program for Demonstrating Thread States
• The following Java program shows some of the states of a thread defined above.
• FileName: ThreadState.java
// ABC class implements the interface Runnable
2. class ABC implements Runnable
3. {
4. public void run()
5. {
7. // try-catch block
8. try
9. {
10. // moving thread t2 to the state timed waiting
11. Thread.sleep(100);
12. }
13. catch (InterruptedException ie)
14. {
15. ie.printStackTrace();
16. }
• System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+
ThreadState.t1.getState());
• 21. // try-catch block
• 22. try
• 23. {
• 24. Thread.sleep(200);
• 25. }
• 26. catch (InterruptedException ie)
• 27. {
• 28. ie.printStackTrace();
• 29. }
• 30. }
• 31. }
• // ThreadState class implements the interface Runnable
• 34. public class ThreadState implements Runnable
• 35. {
• 36. public static Thread t1;
• 37. public static ThreadState obj;
• // main method
• 40. public static void main(String argvs[])
• 41. {
• 42. // creating an object of the class ThreadState
• 43. obj = new ThreadState();
• 44. t1 = new Thread(obj);
• 45.
• 46. // thread t1 is spawned
• 47. // The thread t1 is currently in the NEW state.
• 48. System.out.println("The state of thread t1 after spawning it - " + t1.getState());
• 49.
• 50. // invoking the start() method on
• 51. // the thread t1
• 52. t1.start();
• 53.
• 54. // thread t1 is moved to the Runnable state
• 55. System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());
• 56. }
• public void run()
• 59. {
• 60. ABC myObj = new ABC();
• 61. Thread t2 = new Thread(myObj);
• 62.
• 63. // thread t2 is created and is currently in the NEW state.
• 64. System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
• 65. t2.start();
• // thread t2 is moved to the runnable state
• 68. System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());
• 70. // try-catch block for the smooth flow of the program
• 71. try
• 72. {
• 73. // moving the thread t1 to the state timed waiting
• 74. Thread.sleep(200);
• 75. }
• 76. catch (InterruptedException ie)
• 77. {
• 78. ie.printStackTrace();
• 79. }
• 81. System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );
• 82.
• 83. // try-catch block for the smooth flow of the program
• 84. try
• 85. {
• 86. // waiting for thread t2 to complete its execution
• 87. t2.join();
• 88. }
• 89. catch (InterruptedException ie)
• 90. {
• 91. ie.printStackTrace();
• 92. }
• 93. System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());
• 94. }
• 96. }
• 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.
• 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:

1. public void run(): is used to perform action for a thread.

2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.

3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

4. public void join(): waits for a thread to die.

5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

6. public int getPriority(): returns the priority of the thread.

7. public int setPriority(int priority): changes the priority of the thread.

8. public String getName(): returns the name of the thread.

9. public void setName(String name): changes the name of the thread.

10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
• 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().
1. 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
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running..."); }
4. public static void main(String args[]){
5. Multi t1=new Multi();
6. t1.start(); } }
• Output:
• thread is running...
Java Thread Example by implementing Runnable interface
FileName: Multi3.java
1.class Multi3 implements Runnable{
2.public void run(){
3.System.out.println("thread is running...");
4.}
5.
6.public static void main(String args[]){
7.Multi3 m1=new Multi3();
8.Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9.t1.start();
10. }
11.}
Output:
thread is running...
• Declarative Programming Paradigm
• Java Database Connectivity (JDBC)
• Java JDBC Tutorial
• 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.
• The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL Call Level
Interface. The java.sql package contains classes and interfaces for JDBC API. 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.
• JDBC Driver
• JDBC Driver is a software component that enables java
application to interact with the database. There are 4 types of
JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to
the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now
discouraged because of thin driver.
• In Java 8, the JDBC-ODBC Bridge has been removed.

• Oracle does not support the JDBC-ODBC Bridge from Java 8.


Oracle recommends that you use JDBC drivers provided by the
vendor of your database instead of the JDBC-ODBC Bridge.
• Advantages:
 easy to use.
 can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is
converted into the ODBC function calls.
• The ODBC driver needs to be installed on the client
machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into native
calls of the database API. It is not written entirely in java.
• Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the each client
machine.
• The Vendor client library needs to be installed on client
machine.
3) Network Protocol driver
The Network Protocol driver uses middleware
(application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It
is fully written in java.
• Advantage:
• No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle
tier.
• Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in
the middle tier.
4) Thin driver
• The thin driver converts JDBC
calls directly into the vendor-
specific database protocol. That is
why it is known as thin driver. It is
fully written in Java language.
• Advantage:
• Better performance than all other
drivers.
• No software is required at client side
or server side.
• Disadvantage:
• Drivers depend on the Database.
• 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 of forName() method
• public static void forName(String className)throws ClassNotFoundException
• Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the
classpath, and then JDBC driver manager can detect and load the driver automatically.
• Example to register the OracleDriver class
• Here, Java program is loading oracle driver to esteblish database connection.
• Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
3) throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "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 of createStatement() method
1. 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 of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");
2. while(rs.next()){
3. System.out.println(rs.getInt(1)+" "+rs.getString(2));
4. }
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 of close() method
public void close()throws SQLException
Example to close connection
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.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
• Example to Connect Java Application with mysql database
• In this example, sonoo is the database name, root is the username and password both.
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
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
• There are many advantages of applet. They are as follows:
• 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.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome",150,150); } }
• myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
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.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome to applet",150,150); } }
7. /*
8. <applet code="First.class" width="300" height="300">
9. </applet>
10. */
• Displaying Graphics in Applet
• java.awt.Graphics class provides many methods for graphics programming.
• Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
3. 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.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
5. 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.
6. 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).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
9. 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.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
• Example of Graphics in applet:
1. import java.applet.Applet;
2. import java.awt.*;
3. public class GraphicsDemo extends Applet{
4. public void paint(Graphics g){
5. g.setColor(Color.red);
6. g.drawString("Welcome",50, 50);
7. g.drawLine(20,30,20,300);
8. g.drawRect(70,100,30,30);
9. g.fillRect(170,100,30,30);
10. g.drawOval(70,200,30,30);
11. g.setColor(Color.pink);
12. g.fillOval(170,200,30,30);
13. g.drawArc(90,150,30,30,30,270);
14. g.fillArc(270,150,30,30,0,180);
15. } }
• myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
• 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:
1. 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:
1. import java.awt.*;
2. import java.applet.*;
3. public class DisplayImage extends Applet {
4. Image picture;
5. public void init() {
6. picture = getImage(getDocumentBase(),"sonoo.jpg"); }
7. public void paint(Graphics g) {
8. g.drawImage(picture, 30,30, this); } }
• myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
• </html>
• Animation in Applet
• Applet is mostly used in games and animation. For this purpose image is required to be moved.
1. Example of animation in applet:import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4. Image picture;
5. public void init() {
6. picture =getImage(getDocumentBase(),"bike_1.gif"); }
7. public void paint(Graphics g) {
8. for(int i=0;i<500;i++){
9. g.drawImage(picture, i,30, this);
10. try{Thread.sleep(100);}catch(Exception e){} } } }
• myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
• 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:
1. import java.applet.*;
2. import java.awt.*; myapplet.html
3. import java.awt.event.*; <html>
<body>
4. public class EventApplet extends Applet implements ActionListener{
<applet code="EventApplet.class"
5. Button b; width="300" height="300">
6. TextField tf; </applet>
7. public void init(){ </body>
8. tf=new TextField(); </html>
9. tf.setBounds(30,40,150,20);
10. b=new Button("Click");

11. b.setBounds(80,150,60,50);
12. add(b);add(tf);

13. b.addActionListener(this);
14. setLayout(null); }

15. public void actionPerformed(ActionEvent e){


16. tf.setText("Welcome"); } }
• Java Swing Tutorial
• Java Swing tutorial 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
• There are many differences between java awt and swing that are given below.

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 Swing follows MVC.
model 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.
• File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5. JButton b=new JButton("click");//creating instance of JButton
6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
7. f.add(b);//adding button in JFrame
8. f.setSize(400,500);//400 width and 500 height
9. f.setLayout(null);//using no layout managers
10. f.setVisible(true);//making the frame visible
11. }
12. }
• 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
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7. add(b);//adding button on frame
8. setSize(400,500);
9. setLayout(null);
10. setVisible(true);
11. }
12. public static void main(String[] args) {
13. new Simple2();
14. }}
• 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.
• In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and disadvantages and
examples to understand the implementation of MVC in Java.
• 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 are as follows:
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
Model Layer public class Employee {
The Model in the MVC design pattern // declaring the variables
acts as a data layer for the application. private String EmployeeName;
It represents the business logic for private String EmployeeId;
private String EmployeeDepartment;
application and also the state of
// defining getter and setter methods
application. The model object fetch public String getId() {
and store the model state in the return EmployeeId; }
database. Using the model layer, rules public void setId(String id) {
are applied to the data that represents this.EmployeeId = id; }
the concepts of application. public String getName() {
Let's consider the following code return EmployeeName; }
snippet that creates a which is also the public void setName(String name) {
first step to implement MVC pattern. this.EmployeeName = name; }
public String getDepartment() {
return EmployeeDepartment; }
public void setDepartment(String Department) {
this.EmployeeDepartment = Department; } }
View Layer EmployeeView.java
As the name depicts, view represents the visualization // class which represents the view
of data received from the model. The view layer public class EmployeeView {
consists of output of application or user interface. It
sends the requested data to the client, that is fetched // method to display the Employee details
from model layer by controller. public void printEmployeeDetails (String EmployeeNa
Let's take an example where we create a view using me, String EmployeeId, String EmployeeDepartment){
the EmployeeView class.
System.out.println("Employee Details: ");
System.out.println("Name: " + EmployeeName);

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


d);
System.out.println("Employee Department: " + E
mployeeDepartment);
}
}
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 private Employee model;
necessary validations. It acts as an private EmployeeView view;
// constructor to initialize
interface between Model and public EmployeeController(Employee model, EmployeeView view) {
View. The requests are then sent this.model = model;
to model for data processing. Once this.view = view; }
// getter and setter methods
they are processed, the data is public void setEmployeeName(String name){
sent back to the controller and model.setName(name); }
then displayed on the view. public String getEmployeeName(){
Let's consider the following code return model.getName(); }
public void setEmployeeId(String id){
snippet that creates the controller model.setId(id); }
using the EmployeeController public String getEmployeeId(){
class. 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 EmployeeControlle }
r(model, view); The MVCMain class fetches the employee data from the
method where we have entered the values. Then it pushes
controller.updateView(); those values in the model. After that, it initializes the view
(EmployeeView.java). When view is initialized, the
//updating the model data Controller (EmployeeController.java) is invoked and bind it
controller.setEmployeeName("Nirnay"); to Employee class and EmployeeView class. At last the
System.out.println("\n Employee Details after updating: " updateView() method (method of controller) update the
); employee details to be printed to the console.
Thank you

You might also like